Jest 嘲笑引用错误

Jest mocking reference error

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

const mockLogger = jest.fn();

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

但是 mockLogger 抛出引用错误。

我知道 jest 试图保护我免于超出模拟的范围,但我需要对 jest.fn() 的引用,以便我可以断言它被正确调用。

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

我怎样才能做到这一点?

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

要让它工作,你必须先模拟,然后导入模块并设置间谍的真正实现:

//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();
});