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?
The problem is that jest.mock
are hoisted to at the begin of the file on run time so const 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:
//mock the module with the spy
jest.mock("./myLoggerFactory", jest.fn());
// import the mocked module
import logger from "./myLoggerFactory"
const mockLogger = jest.fn();
//that the real implementation of the mocked module
logger.mockImplementation(() => (type) => mockLogger)
I want to improve last answer with an example of code working:
import { getCookie, setCookie } from '../../utilities/cookies';
jest.mock('../../utilities/cookies', () => ({
getCookie: jest.fn(),
setCookie: jest.fn(),
}));
// Describe(''...)
it('should do something', () => {
const instance = shallow(<SomeComponent />).instance();
getCookie.mockReturnValue('showMoreInfoTooltip');
instance.callSomeFunc();
expect(getCookie).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With