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

82
Visualizações
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 à 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