Reputation: 352
I have a react application with Vite framework in which I want to write the test cases using Jest. But the issue is jest is unable to read absolute path used in the import statements.
Attaching tsConfig file and jest config file for reference.
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"lib": ["dom", "dom.iterable", "esnext"],
"types": ["./types/fin", "./types/heap", "node", "jest", "vite/client", "vite-plugin-svgr/client"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": false,
"jsx": "react-jsx",
"noImplicitAny": false,
"baseUrl": ".",
"paths": {
"src/*": ["src/*"]
}
},
"include": ["src", "src/config/authConfig.ts"],
"exclude": ["node_modules", "build"]
}
jest.config.json
module.exports = {
preset: 'ts-jest',
collectCoverage: true,
collectCoverageFrom: ['./src/**'],
testEnvironment: 'node',
moduleNameMapper: { '^.+\\.(css|less|gif|jpg|jpeg|svg|png)$': 'module.exports = {};' },
};
Please have a look on the config files and suggest what can done in this.
Error:-
● Test suite failed to run
Cannot find module 'src/pages/page1' from 'src/components/Modules/Module1.tsx'
Require stack:
'src/components/Modules/Module1.tsx'
'src/components/Modules/Module1.test.tsx'
1 | import { useState, useEffect, useContext, useRef } from 'react';
> 2 | import { dummy } from 'src/pages/page1';
| ^
3 | import { dummy2 } from 'src/pages/page';
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
at Object.require (src/components/Modules/Module1.tsx:2:1)
at Object.<anonymous> (src/components/Modules/Module1.tsx.test.tsx:2:1)
Upvotes: 2
Views: 1739
Reputation: 352
To solve this issue in my case I just added this in jest.config.js
moduleNameMapper: { '^.+\\.(css|less|gif|jpg|jpeg|svg|png)$': 'module.exports = {};', 'src/(.*)': '<rootDir>/src/$1' },
Look at the last src part which I have added.
Upvotes: 2