Jest mocking reference error

2019-06-18 15:37发布

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?

2条回答
混吃等死
2楼-- · 2019-06-18 16:13

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();
});
查看更多
地球回转人心会变
3楼-- · 2019-06-18 16:28

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)
查看更多
登录 后发表回答