Jest unit test: setTimeout not firing in async test
Asked Answered
M

4

18

I'm trying to understand how asynchronous testing works in Jest.

What I'm trying to do is similar to an example from the Jest documentation. This works fine ..

function doAsync(c) {
  c(true)
}

test('doAsync calls both callbacks', () => {

  expect.assertions(2);

  function callback1(data) {
    expect(data).toBeTruthy();
  }

  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1);
  doAsync(callback2);
});

But I want to delay the callback invocations so I tried this ....

 function doAsync(c) {
    setTimeout(() => {
      console.log('timeout fired')
      c(true)
    }, 1000)
  }

but the test fails with the message Expected two assertions to be called but received zero assertion calls..

The log message 'timeout fired' doesn't appear in the console.

Please can someone explain why it fails?

Marthamarthe answered 3/10, 2018 at 18:49 Comment(0)
D
40

You need to use jest's timer mocks https://jestjs.io/docs/en/timer-mocks

First you tell jest to use mock timers, then you run the timers within your test.

It would look something like:

function doAsync(c) {
  setTimeout(() => {
      c(true)
    }, 1000)
}

jest.useFakeTimers()

test('doAsync calls both callbacks', () => {

  expect.assertions(2);

  function callback1(data) {
    expect(data).toBeTruthy();
  }

  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1);
  doAsync(callback2);

  jest.runAllTimers(); // or jest.advanceTimersByTime(1000)
});
Danit answered 4/10, 2018 at 3:31 Comment(3)
It seems that now jest.useFakeTimers() needs to be used by every test instead of being declared in the upper scope.Nyctaginaceous
@GiulioG. Thank you for this insight, it solved the issue I was having. My test was mysteriously failing after upgrading Jest from 24 to 26 (along with create-react-app from 3 to 4), so if anyone else sees this: move your call to useFakeTimers inside your test!Pettitoes
It’s a pleasure @Cécile FecherolleNyctaginaceous
L
6

Use of jest.runAllTimers(); can lead to below error:

Ran 100000 timers, and there are still more! Assuming we've hit an infinite recursion and bailing out...

After going through the JEST timer mocks documentation, it occurred to me that the setTimeout goes into infinite recursion as mentioned in the docs. It is recommended to use jest.runOnlyPendingTimers() and this solves the infinite recursion error.

Fast forward and exhaust only currently pending timers (but not any new timers that get created during that process)

jest.runOnlyPendingTimers();

Lynea answered 29/9, 2021 at 8:42 Comment(0)
A
0

In my case, it only worked when I used node:timers/promises. Example:

Code not working:

const sleep = (index: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({});
    }, index * 500);
  });
};

Code working:

import { setTimeout } from 'node:timers/promises';

const sleep = (index: number) => {
  return setTimeout(index * 500);
};
Allerus answered 10/5 at 13:21 Comment(0)
M
-1

Use the below code for the setTime out in your test case.

it('saveSubscription', () => {
  function doAsync(c) {
    setTimeout(() => {
      component.addSubscription();
      expect(component.subscription.freq).toEqual('immediate');
      component.saveSubscription();
      expect(component.subscription.name).toBe('Untitled 1');
    }, 30000);
  }
});
Mert answered 31/5, 2022 at 4:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.