Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Is it possible to mock inner function call?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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);
  });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!