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

173
Vistas
Jest - how to mock a function which is invoked in module creation

I have a function which is called on module creation, and I'd like to ensure that it is actually being used with a test.

// MyComponent.js
import {internalComponentFactory} from './factories';

const InternalComponent = internalComponentFactory([1,2,3]);

export const MyComponent = () => {
  return <InternalComponent locale={'en-us'} />
}

I've tried various flavors of this:

// MyComponent.test.js
import {MyComponent} from './MyComponent';

import {internalComponentFactory} from './factories;

jest.mock('./factories', () => ({
  internalComponentFactory: jest.fn()
}));

describe('src/MyComponent', () => {
  it('leverages the internal component factory', () => {
    expect(internalComponentFactory).toHaveBeenCalledTimes(1);
  });
})

However, this ends up failing the test with a count of 0. Likely the case is a timing issue - the module is created once, and it seems before the mock is even applied.

I have also tried placing a require statement within the actual test, but it intermittently fails.

How would I go about mocking the internalComponentFactory call?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The module can be imported dynamically later in the test using import() function.

I managed to make it work like this:

// import { MyComponent } from './MyComponent';

import { internalComponentFactory } from './factories';

jest.mock('./factories', () => ({
  internalComponentFactory: jest.fn()
}));

describe('src/MyComponent', () => {
  it('leverages the internal component factory', async () => {
    await import('./MyComponent');
    expect(internalComponentFactory).toHaveBeenCalledTimes(1);
    expect(internalComponentFactory).toHaveBeenCalledWith([1, 2, 3]);
  });
})

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