【问题标题】:Jest 27: How to reset mock for jest.spyOn(window, "setTimeout")?笑话 27:如何重置 jest.spyOn(window, "setTimeout") 的模拟?
【发布时间】:2022-05-06 17:47:46
【问题描述】:

我正在将一个项目从 jest 版本 26 更新到 jest 版本 27。作为更新的一部分,我不得不从 setTimeout 上的断言切换到 jest.spyOn(window, "setTimeout") 上的断言。

我想全局定义 spy 并在每次测试之前将其重置,例如:

const timeoutSpy = jest.spyOn(window, "setTimeout");
beforeEach(() => {
    jest.resetAllMocks();
});

此代码没有按我的预期工作。 expect(timeoutSpy).toHaveBeenCalledTimes(n) 的断言因预期 (n) 和接收 (0) 呼叫数不匹配而失败。

在每次测试之前重置全局定义的 timeoutSpy 的正确方法是什么?

谢谢。

【问题讨论】:

    标签: unit-testing jestjs mocking


    【解决方案1】:

    你应该使用jest.restoreAllMocks()

    将所有模拟恢复到其原始值。相当于在每个模拟函数上调用 .mockRestore()。请注意,jest.restoreAllMocks() 仅在使用 jest.spyOn 创建模拟时才有效;其他模拟将需要您手动恢复它们。

    【讨论】:

      【解决方案2】:

      beforeEach 中使用jest.resetAllMocks(); 就足够了。下面的代码可以用来证明:

      function callTimeout() {
        setTimeout(() => {
          console.log('hello');
        })
      }
      
      const timeoutSpy = jest.spyOn(window, 'setTimeout');
      
      describe("test timeout", () => {
        beforeEach(() => {
          jest.resetAllMocks();
        });
      
        it("test 1", () => {
          callTimeout();
          callTimeout();
          expect(timeoutSpy).toHaveBeenCalledTimes(2);
        })
      
        it("test 2", () => {
          callTimeout();
          callTimeout();
          expect(timeoutSpy).toHaveBeenCalledTimes(2);
        })
      });
      

      我必须将jest.config.js 文件中的testEnvironment 属性测试到jsdom 才能使window 变量起作用。但是,您可以将 window 替换为 global 以使用默认值 node

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-01
        • 2021-07-03
        • 2019-07-23
        • 1970-01-01
        • 2018-12-31
        • 2019-03-03
        • 1970-01-01
        相关资源
        最近更新 更多