I am writing some code, I have a dummy scenario of what I am trying to achieve show below. I have a function that I am testing, that uses functions from the a different module. I want to mock the functions for the imported module. How do I go about doing it?
I have seen this solution, but the jest.doMock
function does not work in commonJS - is what I understand. This is for a node backend project.
Any help would be appreciated. Thanks
// helper.js
let add = (a, b) => a + b;
let mult = (a, b) => a * b;
module.exports = { add, sub, mult };
// index.js
const { add, mult } = require('./helper');
const add5thenMultiply2 = (a) => {
const res1 = add(a, 5);
return mult(res1, 2);
};
module.exports = { add5thenMultiply2 };
// index.test.js
const { add5thenMultiply2 } = require('./index');
describe('index', () => {
it('returns right value', () => {
const input = 3;
const expected = 16;
const result = add5thenMultiply2(input);
expect(result).toEqual(expected);
});
it('works with mock', () => {
// mock add() such that it always returns 100, but for this test only
const input = 3;
const expected = 200;
const result = add5thenMultiply2(input);
expect(result).toEqual(expected);
});
});