My attempt to write unit test cases has hit a roadblock. Whenever I run the command npm run test for a specific file, I encounter an error Cannot find module '@decorators'
for the named exports that I have included in my application. The same issue arises for another named export @entities
. Below is the content of my jest config file located in the root folder. Just to provide some context, I am working on a nestjs project.
module.exports = {
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: '.',
testEnvironment: 'node',
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
moduleNameMapper: {
'^@entities/(.*)$': 'src/entities/$1',
'^@decorators/(.*)$': 'src/utils/decorators/$1',
},
};
I'm seeking assistance in resolving this issue. I've tried various approaches in the jest config but none seem to be effective.
Here's the updated jest config in package.json:
"jest": {
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/$1",
"^@decorators/(.*)$": "<rootDir>/utils/decorators/$1",
"^entities/(.*)$": "<rootDir>/entities/$1"
},
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
Error details:
Test suite failed to run
Cannot find module '@decorators' from 'modules/test2/entities/test2.entity.ts'
Require stack:
modules/test2/entities/test2.entity.ts
modules/test1/entities/test1.entity.ts
entities/index.ts
modules/test-module/test.service.ts
modules/test-module/test.service.spec.ts
1 | import { ObjectType } from '@nestjs/graphql';
2 | import { Entity } from 'typeorm';
> 3 | import {
| ^
4 | TimestampColumnOptional,
5 | StringColumnOptional,
6 | IntColumnOptional,
at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:428:11)
In my entity file, I have added custom decorators which are imported as shown in the example below. While the project functions correctly, the issue only arises during unit testing.
import {
IntColumnOptional,
StringColumnOptional,
BooleanColumnOptional
} from '@decorators';