Reputation: 81
Based on guidance from (https://facebook.github.io/create-react-app/docs/importing-a-component#absolute-imports) I have tried to run Jest tests on two components in my project (https://github.com/refayathaque/k1y0b1eahsqztk48) that import other components and libraries.
When running the application locally the absolute path imports work fine and everything renders as expected, but during Jest testing, absolute path imports do not work I believe.
I was using the 'NODE_PATH=src/' in the '.env' file before, but CRA3 recommends we do not and instead use the 'jsconfig.json' file. I have the 'jsconfig.json' file but the tests are still not running. The code below is what I have in the 'jsconfig.json' file:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
Error message from Jest:
Test suite failed to run
/Users/refayathaque/Documents/k1y0b1eahsqztk48/node_modules/react-s3/lib/ReactS3.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Signature from "./Signature";
^^^^^^^^^
SyntaxError: Unexpected identifier
Upvotes: 2
Views: 1357
Reputation: 1993
I finally managed to fix this. What was important was that the rootDir
was the same as the baseUrl
in the tsconfig.json
, and that the moduleNameMapper
of jest
also included the correct mapping.
So here's what works in my setup:
In tsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {},
"rootDir": ".",
// ...
},
"include": ["."],
"exclude": [
// ...
]
}
and in your jest
config, wherever that is, regardless if you created your app with create-react-app
or not:
"jest": {
"moduleNameMapper": {
"src(.*)$": "<rootDir>/src$1"
}
},
My .env
file includes: NODE_PATH=src/
.
This works for imports like this one:
import {StyledDropdown} from 'src/components';
This is for a project created using create-react-app
([email protected]
), not ejected, using [email protected]
.
Upvotes: 1