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

163
Visualizações
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 Respostas
Responde à pergunta

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