-1

Let's imagine I have a module as below:

// utils.ts
function innerFunction() {
  return 28;
}

function testing() {
  return innerFunction();
}

export {testing}

I would like to write a unit test to test testing and just mock return value of innerFunction, expecting that any call to innerFunction will just resolve to a certain value, something like below:

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

  return {
    // __esModule: true,
    ...originalModule,
    innerFunction: jest.fn().mockReturnValue(33),
  };
});

import { testing } from '../utils';

  it('should be okay', () => {
    expect(testing()).toBe(33);
  });

I was expecting jest.requireActual will be able to read all functions and innerFunction: jest.fn().mockReturnValue(33) will actually cause any innerFunction invocation to just return 33 as value, but from the little experiment as above it seems like it's not the case.

In actual call innerFunction will be returning 28, but in Jest environment I would like innerFunction to be able to resolve to any value that I would like to

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Isaac
  • 12,042
  • 16
  • 52
  • 116
  • Does this answer your question? [How to mock functions in the same module using Jest?](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) – jonrsharpe Jan 24 '22 at 08:09
  • But the real answer is: you _shouldn't_ like to. Respect the module boundary or move it, test _behaviour_ not implementation details. – jonrsharpe Jan 24 '22 at 08:10

1 Answers1

0

Option 1

Try to pass innerFunction as a dependency of testing

utils.ts

function testing(innerFunction: () => number)  {
  return () => innerFunction();
}

export {testing}

test.ts

import { testing } from '../utils'  
  it('should be okay', () => {
    const mock = () => 33

    // AKA System under test
    const sut = testing(mock)

    expect(sut()).toBe(33);
  });

Tests can be more simple without jest, and more predictable too...

Option 2

Move innerFunction to another file, and use jest.mock

innerFunction.ts

export function innerFunction()  {
      return 33
}

utils.ts

import { innerFunction } from './innerFunction.ts'

function testing()  {
    return innerFunction();
}

export { testing }

test.ts

jest.mock('./innerFunction', () => {
  return () => 33
});

import { testing } from '../utils'

  it('should be okay', () => {
    expect(testing()).toBe(33);
  });