klugjo
klugjo

Reputation: 20885

Jest Mock Several Components at one go

I would like to do something like

[
  { path: 'path1', comp: () => <div>comp 1</div> },
  { path: 'path2', comp: () => <div>comp 2</div> },
].forEach(({ path, comp }) => {
  jest.mock(path, {
    __esModule: true,
    default: comp
  })
});

But I get the following error: The module factory of 'jest.mock()' is not allowed to reference any out-of-scope variables.

Any idea on how to do that ?

I have tried with a simple for loop as well but I get the same error.

Upvotes: 0

Views: 667

Answers (2)

skyboyer
skyboyer

Reputation: 23705

jest.mock is really tricky thing since it should be executed before any import actually run. So there are some limitations:

A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time!

I don't know why, even after renaming comp to mockComp code was failing till I removed __esmodule: true. So this passed to me:

[
  { path: 'comp1', mockComp: () => <div>1</div> },
  { path: 'comp2', mockComp: () => <span>2</span> },
].forEach(({ path, mockComp }) => {
  jest.mock(path, () => mockComp);
});

Anyway, even if you find way module to be esModule and code was passed, I still believe that having separate jest.mock() per each module is better maintainable than iteration over config. At least it's really easy to add, delete and mix inline mocks alongside automocks jest.mock('module1'); that relies on code in __mocks__ folder(unlike approach with forEach and config object)

Upvotes: 2

Teneff
Teneff

Reputation: 32158

Probably you can create a mock component

__mocks__/dummyComponent.jsx
export default () => <div>comp 1</div>;

and then use jest's moduleNameMapper configuration

package.json
{
  // ...
  "jest": {
     "moduleNameMapper": {
       "path1|path2$": "<rootDir>/__mocks__/dummyComponent.jsx"
     }
  }
}

Upvotes: 0

Related Questions