假设我有一个模块需要在应用程序启动时初始化一次(以传递配置)。模块看起来像这样:
MyModule.js
let isInitiazlied;
const myModule = {
init: function() {
isInitiazlied = true;
},
do: function() {
if (!isInitiazlied)
throw "error"
//DO THINGS
}
}
export default myModule;
我想用玩笑对其进行单元测试。测试文件看起来像这样:
MyModule.test.js
import myModule from './MyModule'
describe('MyModule', () => {
describe('init', () => {
it('not throws exception when called', () => {
expect(() => myModule.init()).not.toThrow();
});
})
describe('do', () => {
it('throw when not init', () => {
expect(() => myModule.do()).toThrow();
});
})
})
当我运行测试时,第二个测试失败,因为模块已经初始化,因此不会引发异常。 我尝试在 beforeEach 中使用 jest.resetModules() ,但这不起作用。
有没有办法解决它(不同的模块模式/测试用例)?
您必须重新导入或重新要求您的模块。 检查文档或此问题以获取更多信息:
https://github.com/facebook/jest/issues/3236
https://jestjs.io/docs/jest-object#jestresetmodules
describe('MyModule', () => {
beforeEach(() => {
jest.resetModules()
});
describe('init', () => {
const myModule = require('./MyModule');
it('not throws exception when called', () => {
expect(() => myModule.init()).not.toThrow();
});
})
describe('do', () => {
const myModule = require('./MyModule');
it('throw when not init', () => {
expect(() => myModule.do()).toThrow();
});
})
})
@ltamajs 解决方案非常适合
require
,但如果您使用 import
,那么您将收到下一个错误。
SyntaxError: /path/to/test/file.js: 'import' and 'export' may only appear at the top level
babel-plugin-dynamic-import-node
插件,然后重置模块。总的来说,它看起来像这样:
describe('MyTests', () => {
let MyModule;
beforeEach(() => {
return import('../module/path').then(module => {
MyModule = module;
jest.resetModules();
});
});
test('should test my module', () => {
expect(MyModule.aMethod).not.toBeUndefined();
});
});
来源:https://github.com/facebook/jest/issues/3236#issuecomment-698271251
就我而言,仅重新要求是行不通的。我浏览了笑话文档并找到了this。 这建议使用jest.resetModules()。 这基本上只是重置缓存,并在重新请求模块时确保它从头开始加载。 因此,当您需要重新要求时,请使用它来确保它从头开始加载