Jest 模拟模块多次使用不同的值 [英] Jest mock module multiple times with different values

查看:27
本文介绍了Jest 模拟模块多次使用不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要测试的函数,该函数使用了导入的模块:

I have a function that I want to test and this function uses an imported module:

var a = require('./a');

function add(b) {
  return a + b;
}

module.exports = add;

a 模块在此示例中返回一个数字,但在我的实际项目中,我将其用作不时手动更改的配置对象.

That a module returns a number in this sample, but in my real project I use that as a config object that is changed from time to time manually.

var a = 1;
module.exports = a;

add 函数的测试如下所示:

The test for the add function looks like this:

describe('add', () => {

  it('should add the mock number 1 to 2', () => {
    jest.setMock('./a', 1);
    const add = require('./add');
    expect(add(2)).toBe(3);
  });

  it('should add the mock number 2 to 2', () => {
    jest.setMock('./a', 2);
    const add = require('./add');
    expect(add(2)).toBe(4);
  });
});

第一个测试通过,第二个测试失败,因为它继承了第一个模拟.有没有办法多次模拟 a 模块?

First test passes, The second test fails because it inherits from the first mock. Is there any way to mock the a module multiple times?

我想要一个不暗示重构 add 函数而是专注于多次模拟该模块的解决方案.(在我的真实项目中是一个配置文件)

I would like a solution that doesn't imply refactoring the add function and instead focus on mocking that module multiple times. (in my real project that is a config file)

您可以在此处使用代码:https://repl.it/@adyz/NocturnalBadComma

You can play around with the code here: https://repl.it/@adyz/NocturnalBadComma

推荐答案

添加

beforeEach(() => {
    jest.resetModules();
});

最终测试

describe('add', () => {

    beforeEach(() => {
        jest.resetModules();
    });

    it('should add the mock number 5 to 2', () => {
        jest.setMock('./a', 5);
        const add = require('./add');
        expect(add(2)).toBe(7);
    });

    it('should add the mock number 2 to 2', () => {
        jest.setMock('./a', 2);
        const add = require('./add');
        expect(add(2)).toBe(4);
    });
});

演示:https://repl.it/repls/TrustingBelatedProprietarysoftware

这篇关于Jest 模拟模块多次使用不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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