dumazy
dumazy

Reputation: 14435

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 "../src/ModuleA"

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

    it("should return the mock name", () => {
        const name = ModuleA.getModuleName()
        expect(name).toBe("mockModuleA")
    })
})

my code:

// src/ModuleA.js
export default {
    getModuleName: () => "moduleA"
}

// src/__mocks__/ModuleA.js
export default {
    getModuleName: () => "mockModuleA"
}

I think I followed everything the documentation says about manual mocks, but perhaps I'm overlooking something here? This is my result:

Expected value to be:
      "mockModuleA"
Received:
      "moduleA"

Upvotes: 26

Views: 68583

Answers (2)

Sven Tschui
Sven Tschui

Reputation: 1425

This answer is not strictly related to the OPs question but google lead me here for a similar issue where jest.mock('module', () => ({})) in the root of a file did not work. In my case it was caused by cyclic dependencies. So if jest suddenly starts to ignore calls to jest.mock() then you might want to check for cyclic dependencies in your files.

Upvotes: 5

Estus Flask
Estus Flask

Reputation: 222369

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

import ModuleA 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", () => {
        const ModuleA = 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.

Upvotes: 39

Related Questions