当将 jest
与 ES6 模块和 babel-jest
一起使用时,所有 jest.mock
调用都是 hoisted .
假设我想为测试的类模拟 fs
模块,但保留其余模块的原始实现(例如我在测试期间使用的一些实用程序)。
考虑以下示例:
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(模块名称,工厂,选项)
When using
babel-jest
, calls tomock
will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
jest.dontMock(模块名称)
When using
babel-jest
, calls tounmock
will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
所以在你的情况下我会尝试类似的事情
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'
})
关于javascript - 用于单一导入的 Jest 模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53024136/