Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 495
dumazy Avatar asked Apr 06 '18 13:04

dumazy


People also ask

Does Jest mock get hoisted?

But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest.mock calls to the top of the module (before any imports). To learn more about this and see it in action, see this repo.

What is Jest fn () do?

The Jest library provides the jest. fn() function for creating a “mock” function. An optional implementation function may be passed to jest. fn() to define the mock function's behavior and return value. The mock function's behavior may be further specified using various methods provided to the mock function such as .

Can I use Jest mock inside a test?

mock() doesn't work inside tests, only outside tests.

How do I reset my mock in Jest?

To reset Jest mock functions calls count before every test with JavaScript, we can call mockClear on the mocked function or clearAllMocks to clear all mocks. afterEach(() => { local. getData. mockClear(); });


1 Answers

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.

like image 109
Estus Flask Avatar answered Oct 11 '22 23:10

Estus Flask