Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my async Jest test not failing when it should?

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?

like image 629
Luke Willis Avatar asked Dec 04 '22 23:12

Luke Willis


1 Answers

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.

like image 173
Luke Willis Avatar answered Jan 30 '23 10:01

Luke Willis