Jest嘲笑参考错误

时间:2017-03-08 17:05:40

标签: unit-testing jestjs

我试图使用以下模拟:

const mockLogger = jest.fn();

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

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

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

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

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:9)

问题是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)

答案 1 :(得分:1)

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