I am trying to run test for my react application in which I used @ import such as
import { something } from "@atoms";
I did the mapping in the tsconfig.json file and it s used correctly when I run the application (command: "webpack serve --port 9004") but when I try to test (command "cross-env BABEL_ENV=test jest") the imports fails with this error:
Configuration error:
Could not locate module @atoms mapped as:
[
"src/components/atoms/index"
].
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/@atoms/": "[
"src/components/atoms/index"
]"
},
"resolver": undefined
}
1 | import { ReactElement } from "react";
2 |
> 3 | import { Something } from "@atoms";
| ^
4 |
5 |
6 | export const SomethingElse = ({
at createNoMappedModuleFoundError (../node_modules/jest-resolve/build/resolver.js:579:17)
at Object.<anonymous> (components/molecules/SomethingElse/index.tsx:3:1)
jest.config.js:
const { compilerOptions } = require("./tsconfig.json");
module.exports = {
rootDir: "src",
testEnvironment: "jsdom",
transform: {
"^. \\.(j|t)sx?$": "babel-jest",
},
moduleNameMapper: {
"\\.(sass)$": "identity-obj-proxy",
"single-spa-react/parcel": "single-spa-react/lib/cjs/parcel.cjs",
...compilerOptions.paths,
},
setupFilesAfterEnv: ["@testing-library/jest-dom"],
};
tsconfig.json:
{
"extends": "ts-config-single-spa",
"compilerOptions": {
"jsx": "react-jsx",
"target": "ES5",
"baseUrl": ".",
"paths": {
"@app/*": ["src/*"],
"@configs/*": ["src/configs/*"],
"@configs": ["src/configs/index"],
"@components/*": ["src/components/*"],
"@components": ["src/components/index"],
"@constants/*": ["src/constants/*"],
"@constants": ["src/constants/index"],
"@enums/*": ["src/enums/*"],
"@enums": ["src/enums/index"],
"@hooks/*": ["src/hooks/*"],
"@hooks": ["src/hooks/index"],
"@services/*": ["src/services/*"],
"@services": ["src/services/index"],
"@store/*": ["src/store/*"],
"@store": ["src/store/index"],
"@themes/*": ["src/themes/*"],
"@themes": ["src/themes/index"],
"@utils/*": ["src/utils/*"],
"@utils": ["src/utils/index"],
"@types/*": ["src/types/*"],
"@types": ["src/types/index"],
"@assets/*": ["public/assets/*"],
"@atoms": ["src/components/atoms/index"],
"@molecules": ["src/components/molecules/index"],
"@organisms": ["src/components/organisms/index"],
"@pages": ["src/components/organisms/pages/index"]
}
},
"files": ["src/main-file.tsx"],
"include": ["src/**/*"]
}
CodePudding user response:
I use the tsconfig-paths-jest npm package to add this to use the pathing from the tsconfig.json.
To add it into my Jest setup, I have this in the jest configuration script file (.js)
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);
module.exports = {
moduleNameMapper,
...
};