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

96
Visualizações
Get rid of duplicate jest.mock

Using the same jest.mock, returning different results, leads to the accumulation of duplicate code.

I did not find information on how to deal with this and I would like to ask if it is possible to create a function similar to the following:

const createMock = (result) => jest.mock('some-module', () => (result));
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No, It is Immpossible. You should always write a new mock at the top of describe

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use jest.mock() in the module scope of the test file. It will be hoisted to the top of the file before any import. Which means the imported module is already mocked. So that you can use mock.mockReturnValue() method in each test case to provide a different return value.

E.g.

index.js:

import someFn from './some-module';

export default function main() {
  return someFn();
}

some-module.js:

export default function someFn() {
  return 'a';
}

index.test.js:

import main from './';
import someFn from './some-module';

jest.mock('./some-module');

describe('71219584', () => {
  test('should pass 1', () => {
    someFn.mockReturnValue('fake a');
    console.log(main());
  });
  test('should pass 2', () => {
    someFn.mockReturnValue('fake b');
    console.log(main());
  });
});

Test result:

 PASS  stackoverflow/71219584/index.test.js
  71219584
    ✓ should pass 1 (17 ms)
    ✓ should pass 2 (2 ms)

  console.log
    fake a

      at Object.<anonymous> (stackoverflow/71219584/index.test.js:18:13)

  console.log
    fake b

      at Object.<anonymous> (stackoverflow/71219584/index.test.js:22:13)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.186 s
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