I have some asynchronous actions that I need to test with Jest. My test is currently passing when it should fail.
describe('Asynchronous Code', () => {
it('should execute promise', () => {
console.log(1);
someFunctionThatReturnsAPromise()
.then(() => {
console.log(2);
expect(true).toBeFalsy();
console.log(3);
});
console.log(4);
});
});
When I run npm test
, I get the following output:
PASS __tests__/Async.test.js
● Console
console.log __tests__/Async.test.js:3
1
console.log static-content-test/react/actions/DashboardActions.test.js:6
2
console.log static-content-test/react/actions/DashboardActions.test.js:10
4
As you can see, the test is passing, but console.log(3)
is never executed because true
is not falsy, and the expectation fails.
How can I get Jest to recognize my expectations inside async callbacks?
When testing asynchronous code, you need to return the promise from the test. Change the test body to:
return someFunctionThatReturnsAPromise()
.then(() => {
expect(true).toBeFalsy();
});
With that, the test fails as expected:
FAIL __tests__/Async.test.js
● Asynchronous Code › should execute promise
expect(received).toBeFalsy()
Expected value to be falsy, instead received
true
This is the pattern facebook uses for testing async code with jest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With