Skip to content Skip to sidebar Skip to footer

Manual Mock Not Working In With Jest

Can somebody help me with manual mocking in Jest, please? :) I try to have Jest use the mock instead of the actual module. my test: // __tests__/mockTest.js import ModuleA from '

Solution 1:

Module mocks are hoisted when possible with babel-jest transform, so this will result in mocked module:

importModuleA from"../src/ModuleA"
jest.mock("../src/ModuleA") // hoisted to be evaluated prior to import

This won't work if a module should be mocked per test basis, because jest.mock resides in beforeEach function.

In this case require should be used:

describe("ModuleA", () => {
    beforeEach(() => {
        jest.mock("../src/ModuleA")
    })

    it("should return the mock name", () => {
        constModuleA = require("../src/ModuleA").default;
        const name = ModuleA.getModuleName()
        expect(name).toBe("mockModuleA")
    })
})

Since it's not an export but a method in default export that should be mocked, this can also be achieved by mocking ModuleA.getModuleName instead of entire module.

Post a Comment for "Manual Mock Not Working In With Jest"