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
}));