Jest mocking reference error

前端 未结 2 1747
你的背包
你的背包 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: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)
    

提交回复
热议问题