I am facing an issue with Jest in my Nx workspace where I have a React app, several libraries, and a buildable library. Each library and the React app has its own Jest configuration, and I have a base Jest configuration that is extended within the libraries. Additionally, I have a __mocks__ folder in each library and the root of the repository to make axios work as expected.
However, when running tests for the React app, I encounter the following warning:
jest-haste-map: duplicate manual mock found: axios
The following files share their name; please delete one of them:
* <rootDir>/__mocks__/axios.js
* <rootDir>/libs/redux/__mocks__/axios.js
* <rootDir>/libs/my-custom-lib/__mocks__/axios.js
* <rootDir>/libs/services/__mocks__/axios.js
This warning is due to the existence of the __mocks__ folder multiple times, including in the root of the repository for the main app to function properly.
I have tried creating a central __mocks__ folder, using moduleDirectories within my Jest configuration, renamed the axios.js files based on the library names and tried some apporaches within the jest.setup.ts file. None of them seem to resolve the issue.
Is there a recommended way to structure Jest configurations and __mocks__ folders in an Nx standalone repository with a React app and Nx libraries to avoid these warnings? My goal is to have only ony __mocks__ folder in the root of the repository.
For anyone who has the same problem, here is the solution that worked for me.
Place the
__mocks__directory at the root (same level as yournode_modules) of your Nx workspace (works for standalone repositories as well as mono repositories):myWorkspace/__mocks__.In your
jest.preset.js/tsfile (at the root level as well) do the following:This way you only need one single
__mocks__folder that is also recognized by the Nx libraries inside the same repository.Works with the latest Nx version (17.2.8) as well.