rahul kumar
rahul kumar

Reputation: 33

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.

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

Upvotes: 1

Views: 506

Answers (1)

rahul kumar
rahul kumar

Reputation: 33

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.

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

Upvotes: 2

Related Questions