3
votes

I have a method to trigger a pause using a promise with a setTimeout:

pause = ({ time } = {}) => {
  const pauseTime = time || 500;

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, pauseTime)
  })
}

I want to test it with jest, expecting the timeout function gets the time argument that pause method receives.

jest.useFakeTimers();

const setTimeoutSpy = spyOn(window, 'setTimeout')
const pausePromise = pause({ time: 2500 })


await jest.runAllTimers();

pausePromise.then(() => {
  expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
  expect(setTimeoutSpy).toHaveBeenCalledWith(2500);
})

jest.useRealTimers();
return pausePromise

I tried with mocks and spies. Also tried without timers and awaiting the promise. But I always get the same result: Expected spy to have been called one time, but it was called zero times.

Any idea?

Thanks!

2
You're spying on the setTimeout after you've called the method you are testing. You need to do it before hand. - Taplar
You're right. I moved the spy before the method, but still not working. - Rodrigo

2 Answers

2
votes

Finally I found the issue. It was a problem with the spy implementation:

  1. I was doing spyOn(... instead of jest.spyOn(...
  2. I changed the object I was spying on from window to global

Thanks all for your comments!

1
votes

It works for jest: ^24.9.0.

E.g.

index.ts:

export const pause = ({ time } = {} as any) => {
  const pauseTime = time || 500;

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, pauseTime);
  });
};

index.test.ts:

import { pause } from './';

jest.useFakeTimers();

describe('65135435', () => {
  it('should pass', async () => {
    const setTimeoutSpy = jest.spyOn(window, 'setTimeout');
    const pausePromise = pause({ time: 2500 });

    jest.runAllTimers();

    await pausePromise;
    expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), 2500);
    expect(setTimeoutSpy).toHaveBeenCalledTimes(1);
  });
});

unit test result:

 PASS  src/stackoverflow/65135435/index.test.ts
  65135435
    ✓ should pass (6ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |    33.33 |      100 |      100 |                   |
 index.ts |      100 |    33.33 |      100 |      100 |               1,2 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.119s