2017-03-08 81 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(); 
});