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

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

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

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 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