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

友人

假设我有一个模块,需要在应用程序启动时初始化一次(以传递配置)。模块将如下所示:

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(),但这没有用。

有没有办法解决它(不同的模块模式/测试用例)?

ltamajs

您必须重新导入或重新需要您的模块。查看文档或此问题以获取更多信息:

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();
        });
    })
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章