简体   繁体   English

无法在玩笑中模拟模块

[英]Unable to mock module in jest

I am unable to mock the module in jest我无法开玩笑地模拟模块
when I use the below code test case fails当我使用下面的代码测试用例失败时

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

but when I use the arrow function tets case passes.但是当我使用箭头函数 tets case pass 时。

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

Is there any difference between the two approaches or I am doing something wrong.这两种方法有什么区别,或者我做错了什么。

Below is the implementation.下面是实现。

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

Thanks in advance提前致谢

I was able to figure out the issue.我能够弄清楚这个问题。 There was nothing wrong with the implementation.实施没有任何问题。 Just a config was missing in the package.json file. package.json 文件中只缺少一个配置。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM