如何重置测试之间导入的模块 [英] how to reset module imported between tests

查看:125
本文介绍了如何重置测试之间导入的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

let's say I have a module that needs to be initialized once in the start of the app (to pass on configuration). module will look something like this :

MyModule.js

let isInitiazlied;

const myModule = {

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

export default myModule;

我想用玩笑对它进行单元测试。测试文件如下所示:

I want to unittest it, using jest. test file looks something like this :

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

when I run the test, the 2nd test fail, as the module already initialized so the exception is not thrown. I tried using jest.resetModules() in beforeEach, but that didn't work.

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

Is there a way to solve it (different module pattern/test case) ?

推荐答案

您必须重新导入或重新请求模块。
检查文档或此问题以获取更多信息:

You have to re-import or re-require your module. Check the doc or this issue for more information:

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

这篇关于如何重置测试之间导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆