[英]Jest mock module for single import
當將jest
與ES6模塊和babel-jest
,所有jest.mock
調用都將被掛起 。
假設我想為測試的類模擬fs
模塊,但保留其余模塊的原始實現(例如,我在測試期間使用的一些utils)。
考慮以下示例:
class UnderTest {
someFunction(){
fs.existsSync('blah');
}
}
class TestUtility {
someOtherFunction(){
fs.existsSync('blahblah');
}
}
考試:
it('Should test someFunction with mocked fs while using TestUtility'', () => {
testUtility.someOtherFunction(); // Should work as expected
underTest.someFunction(); // Should work with mock implementation of 'fs'
})
現在,可以期望通過以下方法模擬fs
模塊以用於UnderTest
而不是TestUtility
。
import {TestUtility} from './test-utility';
jest.mock('fs');
import {UnderTest } from './under-test';
但是,由於吊裝,將對所有模塊模擬fs
模塊(這是不希望的)。
有什么辦法可以實現所描述的行為?
為了避免在測試中嘲笑模塊,應該使用jest.doMock(moduleName, factory, options)
和jest.dontMock(moduleName)
。
jest.doMock(moduleName,factory,options)
使用
babel-jest
,對mock
調用將自動提升到代碼塊的頂部。 如果要明確避免此行為,請使用此方法。
jest.dontMock(模塊名稱)
使用
babel-jest
,對unmock
調用將自動提升到代碼塊的頂部。 如果要明確避免此行為,請使用此方法。
所以在您的情況下,我會嘗試類似
beforeEach(() => {
jest.resetModules();
});
it('Should test someFunction with mocked fs while using TestUtility'', () => {
jest.dontMock('fs');
testUtility.someOtherFunction(); // Should work as expected
jest.doMock('fs', () => {
return ... // return your fs mock implementation;
});
underTest.someFunction(); // Should work with mock implementation of 'fs'
})
您可能應該使用笑話的requireActual
:
const fs = jest.requireActual('fs'); // Unmockable version of jest
class TestUtility {
someOtherFunction(){
fs.existsSync('blahblah');
}
}
從文檔中 :
Jest允許您模擬測試中的整個模塊,這對於測試代碼是否正確地從該模塊調用函數很有用。 但是,有時您可能想在測試文件中使用模擬模塊的一部分,在這種情況下,您要訪問原始實現,而不是模擬版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.