【发布时间】:2019-04-01 02:58:21
【问题描述】:
当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 模块将被 所有模块 模拟(这是不可取的)。
有什么方法可以实现所描述的行为?
【问题讨论】:
标签: javascript unit-testing ecmascript-6 mocking jestjs