Unit testing 笑话模拟参考错误

Unit testing 笑话模拟参考错误,unit-testing,jestjs,Unit Testing,Jestjs,我正在尝试使用以下模拟: const mockLogger = jest.fn(); jest.mock("./myLoggerFactory", () => (type) => mockLogger); 但是mockLogger抛出了一个引用错误 我知道jest试图保护我不超出mock的范围,但是我需要一个对jest.fn()的引用,这样我就可以断言它被正确调用了 我只是在嘲笑这个,因为我在做一个图书馆的由外到内验收测试。否则,我会将对记录器的引用作为参数贯穿始终,而不是模拟

我正在尝试使用以下模拟:

const mockLogger = jest.fn();

jest.mock("./myLoggerFactory", () => (type) => mockLogger);
但是mockLogger抛出了一个引用错误

我知道jest试图保护我不超出mock的范围,但是我需要一个对
jest.fn()
的引用,这样我就可以断言它被正确调用了

我只是在嘲笑这个,因为我在做一个图书馆的由外到内验收测试。否则,我会将对记录器的引用作为参数贯穿始终,而不是模拟


如何实现这一点?

问题是
jest.mock
在运行时被提升到文件的开头,因此
const mockLogger=jest.fn()之后运行

要使其工作,您必须首先模拟,然后导入模块并设置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)

我想通过一个代码工作示例来改进最后一个答案:

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();
});
从“../../utilities/cookies”导入{getCookie,setCookie};
jest.mock('../../utilities/cookies',()=>({
getCookie:jest.fn(),
setCookie:jest.fn(),
}));
//描述(“”…)
它('应该做点什么',()=>{
const instance=shallow().instance();
getCookie.mockReturnValue('showMoreInfoTooltip');
instance.callSomeFunc();
expect(getCookie).toHaveBeenCalled();
});

谢谢。我希望提升更明显!