【问题标题】:JEST expect function toBeCalled inside setTimeoutJEST 期望函数在 setTimeout 内被调用
【发布时间】:2019-04-10 19:18:21
【问题描述】:

我有一个简单的函数,它在 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 的模拟看起来工作正常,因为测试通过了。

只是想知道是否有人可以引导我朝着正确的方向前进。提前致谢。

【问题讨论】:

  • 尝试使测试用例异步。
  • 我试过了,但仍然是同样的失败测试。也许我的语法错误? it('调用 open', async () => { foo(); await setTimeout(); expect(global.open).toBeCalled(); });
  • 试试这个。 it('calls open', async() => { foo(); await expect(global.open).toBeCalled(); });
  • 谢谢 - 但这没有用
  • 在运行检查之前您是否尝试过jest.runAllTimers()

标签: javascript unit-testing jestjs


【解决方案1】:

根据https://jestjs.io/docs/en/timer-mocks 的文档,计时器不仅应该是伪造的,还应该使用jest.runAllTimers(); 运行,如下例所示:

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);
});

【讨论】:

    【解决方案2】:

    您可以模拟您的 global.open 并检查在执行 foo() 时是否调用了它:

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

    【讨论】:

    • 你最好把你的答案解释清楚,以便 OP 或其他用户能够理解你的代码。
    猜你喜欢
    • 2021-09-15
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多