Jest mocking reference error

前端 未结 2 1755
你的背包
你的背包 2021-02-13 12:04

I\'m trying to use the following mock:

const mockLogger = jest.fn();

jest.mock(\"./myLoggerFactory\", () => (type) => mockLogger);

but m

相关标签:
2条回答
  • 2021-02-13 12:39

    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();
    });
    
    0 讨论(0)
  • 2021-02-13 12:55

    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)
    
    0 讨论(0)
提交回复
热议问题