Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
173 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...