Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda