假设我有一个模块需要在应用程序启动时初始化一次(以传递配置)。模块看起来像这样:
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://github.com/facebook/jest/issues/3236
https://jestjs.io/docs/jest-object#jestresetmodules 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();
});
})
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)