【问题标题】:Unable to mock module in jest无法开玩笑地模拟模块
【发布时间】:2021-10-10 09:18:16
【问题描述】:

我无法开玩笑地模拟模块
当我使用下面的代码测试用例失败

jest.mock("./module", () => ({
 method1: jest.fn().mockImplementation(() => "method1"),
}));

但是当我使用箭头函数时,tets case 就通过了。

jest.mock("./module", () => ({
  method1: () => "method1",
}));

这两种方法有什么区别还是我做错了什么。

下面是实现。

//utils.js
export const method1 = () => "method 1";

//App.js
import { method1 } from "./utils.js";
export const showMsg = () => method1();




//App.test.js ( Test case fails)
import { showMsg } from "./App";

jest.mock("./utils.js", () => ({
  method1: jest.fn().mockImplementation(() => "method1"),
}));

describe("test mock", () => {
  it("returns the correct value for Method 1", () => {
    expect(showMsg()).toBe("method1");
  });
});


//App.test.js (Test case success)
import { showMsg } from "./App";

jest.mock("./utils.js", () => ({
  method1: () => "method1",
}));

describe("test mock", () => {
  it("returns the correct value for Method 1", () => {
    expect(showMsg()).toBe("method1");
  });
});

提前致谢

【问题讨论】:

  • 该问题缺乏明确的问题陈述。它究竟是如何失败的?如果有错误,应该完整列出

标签: javascript reactjs unit-testing jestjs


【解决方案1】:

我能够找出问题所在。实施没有任何问题。只是 package.json 文件中缺少一个配置。

"jest": {
    "resetMocks": false,
    "restoreMocks": false
  }

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 1970-01-01
    • 2018-07-25
    • 2017-07-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多