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"
Module mocks are hoisted when possible with
babel-jest
transform, so this will result in mocked module:This won't work if a module should be mocked per test basis, because
jest.mock
resides inbeforeEach
function.In this case
require
should be used: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.