Jest + MockImplementationOnce + 第二次不起作用

Sub*_*raj 13 unit-testing node.js jestjs

我正在使用 JEST 框架对我的 node.js 项目进行单元测试。我用于mockImplementationOnce模拟第三方库方法,如下所示:

jest.mock('abc', () => {
    return { a: { b: jest.fn() } };
  });
const abcjs= require('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}
    ));
  });
});
Run Code Online (Sandbox Code Playgroud)

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

nis*_*ush 15

我昨天在模拟 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
  });
});
Run Code Online (Sandbox Code Playgroud)

基本上,不要模拟整个模块,而只模拟您想要从中获得的功能。