Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...