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
}));
4 1 vote
Article Rating

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

0
Would love your thoughts, please comment.x
()
x