The problem
You've written your create-react-app
application using absolute imports resolved from e.g. a folder named src
but when you run your tests you get a message like this:
The explanation
You may have configured Webpack or the TypeScript compiler to resolve absolute imports from the src
folder but Jest doesn't yet know about that configuration.
You can tell Jest about your absolute import resolution strategy by passing another option to the default create-react-app
test
script. Specifically, it's Jest's modulePaths
option that makes this possible.
The solution
To use Jest's modulePaths
option, add --modulePaths=src
to the end of the test
script in your package.json
. If your imports resolve from the src
folder, for example, you would change the script to this:
Although the image above shows the option being passed to react-scripts-ts
it should work for regular react-scripts
as well. Now if you run your tests Jest is able to resolve your absolute imports.