Jest mock module multiple times with different values

不羁的心 提交于 2020-05-13 06:52:06

问题


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;

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;

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

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?

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)

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


回答1:


Add

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

Final tests

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

Demo: https://repl.it/repls/TrustingBelatedProprietarysoftware



来源:https://stackoverflow.com/questions/49650323/jest-mock-module-multiple-times-with-different-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!