golevelup / nestjs

A collection of badass modules and utilities to help you level up your NestJS applications 🚀
MIT License
2.32k stars 271 forks source link

@golevelup/ts-jest default mocks return an empty object which is inconsistent with jest.fn() which returns undefined. #700

Open billoneil opened 9 months ago

billoneil commented 9 months ago

The docs state

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
    });
github-actions[bot] commented 1 month ago

This issue is stale because it has been open for 30 days with no activity.