mardi 17 décembre 2019

How properly test setTimeout after Promise resolve

How properly test this function.

  1. Set timeout
  2. Callback after timeout
  3. And recursive call
export function initScheduler(timeout: number, callback: () => Promise<void>): void {
  setTimeout(() => {
    callback().then(() => {
      initScheduler(timeout, callback);
    });
  }, timeout);
}

I tried something like

describe('initScheduler', () => {
  it('should call on schedule', () => {
    jest.useFakeTimers();

    const timeout: number = 60000;
    const callback: jest.Mock = jest.fn().mockResolvedValue(undefined);

    initScheduler(timeout, callback);

    expect(setTimeout).toHaveBeenCalledTimes(1);
    expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), timeout);
    expect(callback).not.toBeCalled();

    jest.advanceTimersByTime(timeout);

    expect(callback).toBeCalled();
    expect(setTimeout).toHaveBeenCalledTimes(2);
  });
});

But last expectation returns 1

Aucun commentaire:

Enregistrer un commentaire