How to mock all files in a folder in jest

Viewed 1393

I have files as follows

widgets
|
 --tabs
    |
     -- __mocks_
        |
         -- index.ts
     -- index.ts
 --button
    |
     -- __mocks_
        |
         -- index.ts
     -- index.ts

Its imported/used in files as

import { Button } from 'common/widgets/button';

I can individually mock each of these.

jest.mock('common/widgets/tabs');
jest.mock('common/widgets/button');

But is there a way to mock them all like add all these to file and import them or do like below with a common mock folder and an index file.

jest.mock('common/widgets');
2 Answers

You can do it this way (P.S. All functions and function calls are just for demonstration:

Folder structure

enter image description here

widgets/button/index.js

// demonstration
const someFunction = () => {
  console.log("widgets/button")
}

export default someFunction;

widgets/tabs/index.js

// demonstration
const someFunction = () => {
  console.log("widgets/tabs")
}

export default someFunction;

widgets/index.js

export { default as Button } from './button/index';
export { default as Tabs } from './tabs/index';

-- Usage You can import the functions as named import in any file. E.G.: /any/file.js

import { Button, Tabs } from 'common/widgets'
...

So, you should be able to import them into a single mock file.

mock/index.js

jest.mock('common/widgets');

When we import any module in the test file then jest checks whether there is an mock implementation of that module is present in the ./__mocks__ directory or not. If jest founds it then jest will simple mock that module.

Here in your case, you already have mock modules in your ./__mocks__ directories. You don't need jest.mock() api to mock your modules.

Jest mock is meant to mock modules not directories which contains modules.

Related