Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mocking reference error

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?

like image 875
Joe S Avatar asked Mar 08 '17 17:03

Joe S


2 Answers

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)
like image 108
Andreas Köberle Avatar answered Nov 20 '22 09:11

Andreas Köberle


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();
});
like image 33
Albert Olivé Avatar answered Nov 20 '22 11:11

Albert Olivé