When mocking a jest module the mock referenced in the definition, implementation and test are different, which means I am unable to assert on the mock.
I'm wanting the same mock to be used in each location
Context
I am attempting to spy on a function called from by and action in a React component. I am using react testing library (RTL) and firebase.
Setup
setupTests.ts (using CRA and setting up global mocks)
jest.mock("firebase/functions", () => {
return {
getFunctions: jest.fn(),
httpsCallable: (instance: Functions, methodName: string) => {
return jest.fn().mockName(methodName);
},
};
});
init.ts (initialised in the RTL render)
import functions from "./functions"
...
export const cloudFunctions = functions(fb.functions); // Here cloudFunctions.sendEmail mock is correct
...
/** Functions module
export const functions = (functions: Functions) => ({
sendEmail: httpsCallable(functions, "emailInvite"),
});
*/
memberFunctions.ts (module with code being executed)
import { cloudFunctions } from "./init"
export const inviteMember = () => {
....
// Here the mock looses its name/context it is still a jest.fn() instances however no
// longer has the name set from the mock. Logging here the mock is called and jest.fn
// returns the correct information
cloudFunctions.sendEmail()
....
}
ManageMembers.test.tsx (test file)
import {cloudFunctions} from "./init";
beforeEach(() => {
return jest.clearAllMocks();
});
const mockedSendEmail = jest.mocked(cloudFunctions.sendEmail);
test("should allow administrators to invite members", () => {
// Test has another jest.fn() reference doesn't include the name
// set in the mock also no call information used from the implementation.
console.log("mockedSendEmail", mockedSendEmail.getMockName());
});