Home

Testing asynchronous code using Jest

Testing code after sometime just remind you of the setTimeout functionality in JavaScript.

Problem

But when you simply write a setTimeout inside a test, it wont work. The following code doesn't work:

it('mock async test', () => {
  console.log('This message will be logged immediately');
  setTimeout(() => {
    console.log('This message will logged after 1s');
  }, 1000);
});

In the above test only This message will be logged immediately will get logged in console.

Solution 1: Use Fake Timers

You can use useFakeTimers:

it('mock async test', () => {
  console.log('This message will be logged immediately');

  jest.useFakeTimers();
  setTimeout(() => {
    console.log('This message will logged after 1s');
  }, 1000);
  jest.runAllTimers();
});

Solution 2: Use callback

You can use the callback provided by Jest.

it('mock async test', done => {
  console.log('This message will be logged immediately');

  setTimeout(() => {
    console.log('This message will logged after 1s');
    done();
  }, 1000);
});


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments