I’m currently facing an issue with mocking a function that’s called within another function, both of which are imported from an ECMAScript Module (“.mjs” file). Here is a simplified example to illustrate my problem:
// foo.mjs
// This is the function I want to mock
export function foo1() {
console.log("inside real foo1");
}
// This is the function I want to test
export function foo2() {
foo1();
}
Could anyone provide guidance or examples on how to properly mock foo1 when testing foo2 in this context? Thanks in advance for your help!
Here’s what I have tried:
- using
spyon
describe("", () => {
let x;
beforeAll(async () => {
x = await import("./foo.js");
});
it("", async () => {
// Adding this doesn't work
Object.defineProperty(x, 'foo1', {
value: jest.fn(),
configurable: true,
writable: true,
});
jest.spyOn(x, "foo1"); // TypeError: Cannot assign to read only property 'foo1' of object '[object Object]'
x.foo2();
});
});
I attempted to use jest.spyOn, but I keep encountering the error TypeError: Cannot assign to read only property 'foo1' of object '[object Object]'
. I tried the solution suggested in this Stack Overflow post, using Object.defineProperties
, but that didn’t resolve the issue.
- using
jest.unstable_mockModule
jest.unstable_mockModule(
"./foo.js",
() => ({
foo1: jest.fn()
}),
})
);
describe("", () => {
let x;
beforeAll(async () => {
x = await import("./foo.js");
});
it("", async () => {
x.foo2(); // doesn't work foo2 not found
});
});
I also experimented with jest.unstable_mockModule. This approach seemed to work initially, but only if the functions are in separate files, which does not fulfill my needs as both foo1 and foo2 must remain in the same file.