0

I have two functions in one file

file1.ts:

const function1 = () => {
  return 123;
};
const function2 = () => {
  return function1() + 2;
};

export { function1, function2 };

I'm writing unit tests using jest for function 2. but I'm unable to mock function1

I just tried to use jest.spyOn to mock function1

import * as helperFunctions from 'file1';
describe('test function2 ', () => {
  let functionSpy: any;
  beforeAll(() => {
    functionSpy = jest.spyOn(helperFunctions, 'function1 ');
  });

  afterAll(() => {
    functionSpy.mockReset();
  });
  test('test', () => {
    functionSpy.mockReturnValue(1);
    expect(helperFunctions.function2()).toEqual(3);
  });
});

in my test, function1 is not mocked, it still calls the actual implementation. Any help is appreciated.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
hshi
  • 39
  • 1
  • 4
  • it is not possible to mock module partially. you should consider splitting module into two or just compose your tests in a way when you don't need to mock another function – skyboyer May 30 '19 at 18:30
  • Possible duplicate of [Jest mock inner function](https://stackoverflow.com/questions/51269431/jest-mock-inner-function) – Brian Adams May 31 '19 at 01:53
  • It isn't possible to mock the call to `function1` within `function2` the way the code is currently written...see [my answer here](https://stackoverflow.com/a/55193363/10149510) for details – Brian Adams May 31 '19 at 01:54

1 Answers1

0

Here is the solution:

index.ts:

const function1 = () => {
  return 123;
};
const function2 = () => {
  return exports.function1() + 2;
};

exports.function1 = function1;
exports.function2 = function2;

Unit test:

describe('test function2 ', () => {
  const helperFunctions = require('./');
  helperFunctions.function1 = jest.fn();
  test('test', () => {
    helperFunctions.function1.mockReturnValueOnce(1);
    expect(helperFunctions.function2()).toEqual(3);
  });
});

Unit test result:

 PASS  src/stackoverflow/56354252/index.spec.ts
  test function2 
    ✓ test (8ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.696s, estimated 3s

You can find this issue for more detail: https://github.com/facebook/jest/issues/936#issuecomment-214939935

Lin Du
  • 88,126
  • 95
  • 281
  • 483