Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!