I'm trying to use the following mock:
const mockLogger = jest.fn();
jest.mock("./myLoggerFactory", () => (type) => mockLogger);
but mockLogger throws a reference error.
I know jest is trying to protect me from reaching outside of the scope of the mock, but I need a reference to jest.fn()
so I can assert that it was called correctly.
I'm only mocking this because I'm doing an outside-in acceptance test of a library. Otherwise I would thread the reference to the logger all the way through as a parameter rather than mocking.
How can I achieve this?
I want to improve last answer with an example of code working:
The problem is that
jest.mock
are hoisted to at the begin of the file on run time soconst mockLogger = jest.fn();
is run afterwards.To get it work you have to mock first, then import the module and set the real implementation of the spy: