Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda