首页 > 解决方案 > Jest + MockImplementationOnce + 没有第二次工作

问题描述

我正在使用 JEST 框架对我的 node.js 项目进行单元测试。我使用 mockImplementationOnce 来模拟第三方库方法,如下所示: jest.mock('abc', () => { return { a: { b: jest.fn() } }; }); 常量 abcjs= 要求('abc');

describe("1st test", () => { 
  test("should return true", async () => {
    abcjs.a.b.mockImplementationOnce(() => Promise.resolve(
      return true}
    ));
  });
});

describe("2nd test", () => { 
  test("should return false", async () => {
    abcjs.a.b.mockImplementationOnce(() => Promise.resolve(
      return false}
    ));
  });
});

第一个测试成功执行,但第二个测试它调用实际方法,它不是模拟。 我尝试在 afterEach 之后重置模拟,但没有帮助。

标签: node.jsunit-testingjestjs

解决方案


昨天我在模拟 aws-sdk 时遇到了同样的问题。

事实证明,在你模拟了整个模块一次之后,你不能再次覆盖同一个文件中那个模拟的行为。

我很惊讶您的第一个测试实际上通过了,即使您的默认模拟函数只是一个没有任何返回值的 jest.fn()。

这里有一个完整的讨论 - https://github.com/facebook/jest/issues/2582

来自线程的最终解决方案:

// no mocking of the whole module

const abcjs= require('abc');


describe("1st test", () => { 
  test("should return true", async () => {

    // Try using jest.spyOn() instead of jest.fn

    jest.spyOn(abcjs.a,'b').mockImplementationOnce(() => Promise.resolve(true)));
    //expect statement here
  });
});

describe("2nd test", () => { 

jest.restoreAllMocks(); // <----------- remember to add this

  test("should return false", async () => {
    jest.spyOn(abcjs.a,'b').mockImplementationOnce(() => Promise.resolve(false)));
    // expect statement here
  });
});

基本上,不要模拟整个模块,而只模拟你想要的功能。


推荐阅读