Jest is an open-source testing framework that has become increasingly popular recently. Developed by Facebook and built into the popular packagecreate-react-app
. Jest comes with built-in mocking and assertion abilities. In addition, Jest runs your tests concurrently in parallel, providing a smoother, faster test run.
Asynchronous Tests in Jest
Asynchronous Test Using Promises
Sourcecode in jestasync.js file
const axios = require('axios');
const jestasync = {
fetchUser: () =>
axios
.get("https://jsonplaceholder.typicode.com/users/2")
.then(res => res.data)
.catch(err => 'error')
};
module.exports=jestasync;
Code in jestasync.test.js file
const jestasync=require('./jestasync');
describe("Asynchronous with Promises", () => {
test('asynchronous by returning a promise', ()=> {
expect.assertions(1);
return jestasync.fetchUser().then(data => {
expect(data.name).toEqual('Ervin Howell');
});
});
test('asynchronous functions return promises', async ()=> {
expect.assertions(1);
const data = await jestasync.fetchUser();
expect(data.name).toEqual('Ervin Howell');
});
})
PASS ./jestasync.test.js
Asynchronous
✓ asynchronous by returning a promise (135ms)
✓ asynchronous functions return promises (40ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 2.121s
Ran all test suites.
Asynchronous Using a Callback
Code in jestasync.test.js file
describe("Asynchronous with Callback", () => {
test("asynchronous callback return data", done => {
function callback(data) {
expect(dat.namea).toBe('Ervin Howell');
done();
}
jestasync.fetchUser(callback);
}, 10000);
});
Russell Glista
Bookmarked!, I really like your web site!
Raj
Thank you!
Geraldo Proveaux
Bookmarked!, I like your web site!
Raj
thank you!
Idalia Galey
First time visiting your website, I like it!
Raj
Thank you!
Vincenza Gernatt
Saved as a favorite!, I like your website!
Raj
Thank you!