I am still new in nestjs and i don't understand what happen when i try to make a simple test with jest in nestjs test folder, i already notice the absolute path is not working on the import, so i used relative path, the rest of the app work fine but in app.e2e-spec.ts i got the error when i simply import the app.module.
app.module.ts
import { AuthModule } from './auth/auth.module.js';
import { UserModule } from './user/user.module.js';
import { PrismaModule } from './prisma/prisma.module.js';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true
}),
AuthModule,
UserModule,
PrismaModule
],
})
export class AppModule {}
Simple test in app.e2e-spec.ts
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module.js'; //import relative path
describe('App end2end test', ()=> {
beforeAll(async ()=> {
const moduleRef = await Test.createTestingModule({
imports: [ AppModule ] // this line
}).compile();
})
it.todo('should pass');
})
I check the path there is no mistake, for this project i am using Type: "Module"
in package.json and "moduleResolution": "NodeNext",
in tsconfig.json.
setting in jest-e2e.json
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^. \\.(t|j)s$": "ts-jest"
}
}
ts.config.json
{
"compilerOptions": {
"module": "ES2022",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2022",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"moduleResolution": "NodeNext",
"esModuleInterop": true,
},
}
When i run npm run test:e2e i get this error :
Cannot find module '../src/app.module.js' from 'app.e2e-spec.ts'
could it be the file extension with ts ? looks like the issue is the fact using "moduleResolution": "NodeNext" force me to add extension, while in the app when using "js" extention Typescript know it's a "ts" file, but this could be the issue on testing? what i am doing wrong or missing ?
CodePudding user response:
The path should refer to a .ts
file. You're currently addressing to .js
file.
Change ../src/app.module.js
to ../src/app.module
.
Updated:
Ok, seems like Jest getting confused by .js
files whenever you import them in .ts
files, and couldn't resolve paths.
To fix this, you need to have some changes in jest-e2e.json
:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^. \\.(t|j)s$": ["ts-jest", { "useESM": true }]
},
"moduleNameMapper": {
"^(\\.*/.*)\\.(j|t)s$": "$1"
},
"extensionsToTreatAsEsm": [".ts"]
}