gpt4 book ai didi

javascript - 如何重置测试之间导入的模块

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:46 25 4
gpt4 key购买 nike

假设我有一个模块需要在应用启动时初始化一次(以传递配置)。模块看起来像这样:

MyModule.js

let isInitiazlied;

const myModule = {

init: function() {
isInitiazlied = true;
},
do: function() {
if (!isInitiazlied)
throw "error"
//DO THINGS
}
}

export default myModule;

我想使用 jest 对其进行单元测试。测试文件看起来像这样:

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://facebook.github.io/jest/docs/en/jest-object.html#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();
});
})
})

关于javascript - 如何重置测试之间导入的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48989643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com