1

I have a module in CommonJS, it is like a helper module with a few functions. Some functions in that module call other functions from the same module.

Example:

function someFunctionToMock1(a, b) {
  console.log('Some long fetch function 1 which result needs to be mocked');

  if (b) throw new Error('Just checking if the someFunctionToMock1 is mocked');
  return 'results from someFunctionToMock1';
}

function someFunctionToMock2(a, b) {
  console.log('Some long fetch function 2 which result needs to be mocked');

  if (b) throw new Error('Just checking if the someFunctionToMock2 is mocked');
  return 'results from someFunctionToMock2';
}

function functionToTest(a, b) {
  console.log('My function is starting');

  const resultsFromFunctionToMock1 = someFunctionToMock1(a, b);
  const resultsFromFunctionToMock2 = someFunctionToMock2(a, b);

  if (a && !b) return a;
  if (!a && b) return b;
  return a * b;
}

module.exports = { someFunctionToMock1, someFunctionToMock2, functionToTest };

I am trying to test the functionToTest and mock the rest of the functions like so:

const { functionToTest } = require('.');

jest.mock('.', () => {
  const originalModule = jest.requireActual('.');

  return {
    ...originalModule,
    someFunctionToMock1: jest.fn(() => 'mocked results 1'),
    someFunctionToMock2: jest.fn(() => 'mocked results 2'),
  };
});

test('should do a partial mock', () => {
  const results = functionToTest(2, 3);

  expect(results).toBe(6);
});

However it seems like someFunctionToMock1 and someFunctionToMock2 are not being mocked as I am getting error coming from someFunctionToMock2: Error('Just checking if the someFunctionToMock1 is mocked');

What's wrong here? If I would keep functions someFunctionToMock1 and someFunctionToMock1 in a separate module I would have no problems with mocking those. However I would like to avoid that as the code I have shown is just an example. The real code is a production one and I don't want to change the module I am unit testing.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
kapalkat
  • 396
  • 2
  • 4
  • 11

0 Answers0