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');
Yes, you can use the jest.mock function to mock all the files in the widgets folder at once by using the following code:
jest.mock('common/widgets');
Alternatively, you can create a mock index file in the widgets folder that exports all the mocks for the individual widgets, like this:
// widgets/__mocks__/index.tsexport { default as Tabs } from './tabs'; export { default as Button } from './button';
Then, you can use the jest.mock function to mock the widgets folder and all the widgets inside it by specifying the path to the mock index file:
jest.mock('common/widgets/__mocks__');
Finally, you can import the mocked widgets using the following import statement:
import * as widgets from 'common/widgets';
This will give you an object with all the mocked widgets, which you can use in your tests like this:
widgets.Button.mockImplementation(() => { // mock implementation for Button widget }); widgets.Tabs.mockImplementation(() => { // mock implementation for Tabs widget });