Jest嘲笑参考错误

Joe*_*e S 8 unit-testing jestjs

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

const mockLogger = jest.fn();

jest.mock("./myLoggerFactory", () => (type) => mockLogger);
Run Code Online (Sandbox Code Playgroud)

但是mockLogger引发了一个引用错误.

我知道jest试图保护我不要超出模拟范围,但我需要一个引用,jest.fn()所以我可以断言它被正确调用.

我只是在嘲笑这个因为我正在做一个库的外部验收测试.否则,我会将对logger的引用作为参数而不是模拟进行操作.

我怎样才能做到这一点?

And*_*rle 15

问题是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)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。我希望吊装更明显! (2认同)

Alb*_*ivé 7

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

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();
});
Run Code Online (Sandbox Code Playgroud)