簡體   English   中英

JEST 期望函數在 setTimeout 內被調用

[英]JEST expect function toBeCalled inside setTimeout

我有一個簡單的函數,它在 setTimeout 中打開一個新窗口,並想測試打開的窗口是否被調用。

export function foo() {
     setTimeout(() => {
        window.open('http://google.com');
    }, 0);
 }

describe('foo', () => {
    beforeEach(() => {
        jest.useFakeTimers();
        global.open = jest.fn();
    });

    it('calls open', () => {
        foo();

        expect(setTimeout).toHaveBeenCalledTimes(1);
        expect(global.open).toBeCalled(); //FAILING
    });
});

目前我的期望因“預期的模擬函數已被調用”而失敗。 當我從我的函數中刪除 setTimeout 時,當測試通過時,window.open 的模擬看起來工作正常。

只是想知道是否有人可以引導我朝着正確的方向前進。 提前致謝。

您可以模擬global.open並檢查它是否在執行foo()時被調用:

it('calls open', (done) => {
        global.open = jest.fn(); // mocking global.open
        foo();  // calling foo()

        setTimeout(()=> {
          expect(global.open).toBeCalled()
          done()
        })
})

計時器不僅應該是偽造的,而且還應該使用jest.runAllTimers();運行jest.runAllTimers(); 根據https://jestjs.io/docs/en/timer-mocks上的文檔,如下例所示:

test('calls the callback after 1 second', () => {
  const timerGame = require('../timerGame');
  const callback = jest.fn();
  jest.useFakeTimers();

  timerGame(callback);

  // At this point in time, the callback should not have been called yet
  expect(callback).not.toBeCalled();

  // Fast-forward until all timers have been executed
  jest.runAllTimers();

  // Now our callback should have been called!
  expect(callback).toBeCalled();
  expect(callback).toHaveBeenCalledTimes(1);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM