Reputation: 196
when using React and Jest I encountered a use case for manual mocks, that I do not know how to overcome. Given the following structure:
.
├── code.test.tsx
└── module
├── __mocks__
├── index.tsx
├── module.tsx
└── submodule
├── __mocks__
└── index.tsx
I am writing tests inside code.test.tsx
. The components module
and submodule
do contain manual file mocks that returns dummy code for unit testing purposes.
module/index.tsx
acts as an export point for the component itself and submodule:
export * from './submodule'
export { module } from './module.tsx'
This way the imports inside code.tsx
are more organized:
import { module, submodule } from './module'
Finally inside code.test.tsx
I mock the import of module
by calling jest.mock('./module')
. The desired behavior should be that module
and submodule
are getting mocked since both components contain a __mocks__
folder.
Since module/__mocks__
exports a mock that only defines itself, the underlying components are undefined. In this case I would normally adjust the imports to point to the components directly. But since the imports provide advanced readability I want to recursively mock the subfolders where ever there is a __mocks__
directory. Is it possible to achieve it?
Upvotes: 1
Views: 1608
Reputation: 1752
As per the Jest docs on using manual mocks, it is explicitly required that you mock the module present in the __mocks__
directory.
When we require that module in our tests, explicitly calling jest.mock('./moduleName') is required.
Please ensure you have explicitly mocked the module and submodule imports in your test file.
Upvotes: 1