How mock modules while overriding specific methods in Jest

Suppose you have JS module that uses methods of another module when it’s gets transpiled. Here for example the MainModule uses SubModule method to set newNumber.

// MainModule
import { subFunc } from "./SubModule";

let newNumber = subFunc(3);

export function addTwo() {
    return  2 + newNumber;
}
// SubModule.js
export function subFunc(val) {
    return val * 10;
}

// ... other exports

Now to suppose you want to test addTwo function and mock SubModule also but override the subFunc method only.

For this you can use jest.createMockFromModule(moduleName) along with jest.mock(moduleName).

jest.mock("@/sample/SubModule", () => ({
    ...jest.createMockFromModule('@/sample/SubModule'),
    subFunc: () => 2
}));
0 0 votes
Article Rating

By Sinaru Gunawardena

Sinaru is a software developer at work and a painter in free time. He enjoys writing tech notes on his personal website. He currently lives in Dublin, Ireland.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments