2017-03-08 82 views
1

我尝试使用下面的模拟:玩笑嘲讽引用错误

const mockLogger = jest.fn(); 

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

但mockLogger抛出一个引用错误。

我知道jest正在试图保护我不能达到模拟范围之外,但我需要对jest.fn()的引用,所以我可以断言它是正确调用的。

我只是在嘲笑这个,因为我正在做一个图书馆的外部验收测试。否则,我会将参考记录一直作为参数而不是嘲笑。

我该如何做到这一点?

回答

2

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

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

0

我想改善与代码工作的一个例子最后的答案:

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