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

81
Vistas
Override .mockReturnValue in a single test

I'm trying to mock a module's function. I want it to return a specific value every time until the point that I'm firing a function that should change that value to something else. Assume you can't have any expectations of how many times the module's mocked function will fire before, or after the changing function fires.

What I've tried so far is:

import * as module from 'module';

jest.mock('module', () => ({
  ...jest.requireActual('module'),
  targetFunction: jest.fn(),
}));


test('targetFunction returns a different value after changingFunction has fired', async () => {
  jest
    .spyOn(module, 'targetFunction')
    .mockReturnValue('a');

  module.start();
  // other assertions

  jest
    .spyOn(module, 'targetFunction')
    .mockReturnValue('b');

  module.changingFunction();
  // other assertions
});

But it keeps returning a after my second mock.

Obviously the above is just a demonstration of the expected behaviour. Before changingFunction fires, I want targetFunction to return a every time it fires. After changingFunction fires, I want targetFunction to return b every time it fires.

If I'm using mockReturnValueOnce, and continue to chain them it works, but I wouldn't like to rely on specific times. I want to change the return value in a specific place in the code.

about 4 years ago · Juan Pablo Isaza
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