Home > Net >  Jest - how to mock a function which is invoked in module creation
Jest - how to mock a function which is invoked in module creation

Time:09-24

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?

CodePudding user response:

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]);
  });
})

  • Related