The list goes on with possible problems. Enter @golevelup/ts-jest's createMock utility function. This function will create a mock object for you with all sub properties mocked as jest.fn() unless otherwise provided, to allow for easy mocking later on, but more on that later.
However the behavior doesn't quite seem to match. When we mock a class with createMock the default implementations return {} instead of undefined which is what jest.fn() returns by default. However, once you trigger a jest.resetAllMocks() the mocked functions now return undefined instead of the original {}. This is an odd inconsistency and wondering if this is expected behavior or not.
class MyClass {
helloWorld() {
return "hello world";
}
}
it("resetMocks after first invocation", () => {
const myClassMock = createMock<MyClass>();
// Why does this return `{}` until we reset mocks then it returns undefined
expect(JSON.stringify(myClassMock.helloWorld())).toBe("{}"); // Passes
jest.resetAllMocks();
expect(myClassMock.helloWorld()).toBeUndefined(); // Passes
});
it("reset mocks before invocation", () => {
const myClassMock = createMock<MyClass>();
// Resetting before the first invocation doesn't have this behavior
jest.resetAllMocks();
expect(JSON.stringify(myClassMock.helloWorld())).toBe("{}"); // Passes
expect(myClassMock.helloWorld()).toBeUndefined(); // Fails Received: {} expected undefined
});
The docs state
However the behavior doesn't quite seem to match. When we mock a class with
createMock
the default implementations return{}
instead ofundefined
which is whatjest.fn()
returns by default. However, once you trigger ajest.resetAllMocks()
the mocked functions now returnundefined
instead of the original{}
. This is an odd inconsistency and wondering if this is expected behavior or not.