I am trying to include test in a pretty big and established project. I've managed to configure jest and make it work, but I've encontered a problem when importing using aliases.
Cannot find module '@app/<dir>/<myFile>.<extension>'
My first thought was to change my imports from my test to relative in order to check if the problem were my test. By doing that I only get the same error but now from the imports of the component I mount in the test.
So, I went and looked for a solution to make Jest understand module aliases. I've tried several thing and cannnot make it work, so I hope someone can see what I'm missing and help me to configure it.
Since this is a pretty big project I am trying to avoid updating the Angular version.
Here is all the configuration I have right now:
package.json
...
"dependencies": {
"@angular-devkit/schematics": "9.1.15",
"@angular/animations": "9.1.13",
"@angular/cdk": "9.2.4",
"@angular/common": "9.1.13",
"@angular/compiler": "9.1.13",
"@angular/core": "9.1.13",
"@angular/forms": "9.1.13",
"@angular/material": "9.2.4",
"@angular/material-moment-adapter": "9.2.4",
"@angular/platform-browser": "9.1.13",
"@angular/platform-browser-dynamic": "9.1.13",
"@angular/router": "9.1.13",
...
},
"devDependencies": {
"@angular-builders/jest": "11.1.0",
"@angular-devkit/build-angular": "~0.901.15",
"@angular/cli": "9.1.15",
"@angular/compiler-cli": "9.1.13",
"@angular/language-service": "9.1.13",
"@faker-js/faker": "^7.5.0",
"@testing-library/angular": "10.3.2",
"@testing-library/jest-dom": "5.11.10",
"@testing-library/user-event": "12.7.4",
"@types/jest": "26.0.20",
"@types/lodash": "4.14.157",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"fishery": "^2.2.2",
"jest": "26.6.3",
"jest-preset-angular": "8.3.2",
"ngx-translate-testing": "4.0.0",
"protractor": "~5.1.2",
"ts-jest": "26.5.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "3.8.3"
}
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"downlevelIteration": true,
"importHelpers": true,
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2015",
"resolveJsonModule": true,
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
],
"baseUrl": "src",
"paths": {
"@app/*": [
"app/*"
],
"@env/*": [
"environments/*"
]
},
"module": "esnext",
"esModuleInterop":true
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
jest.config.js
module.exports = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: [
'./jest.setup.ts'
],
transform: {
"^.+\\.tsx?$": "ts-jest"
},
verbose: true,
roots: [ '<rootDir>/src/' ],
moduleNameMapper: {
"@app/(.*)": "<rootDir>/src/app/$1",
},
};
I've also tried configuring moduleNameMapper with "^@app/(.*)$": "<rootDir>/src/app/$1" and a few more variants.
jest.setup.ts
import 'jest-preset-angular';
import '@testing-library/jest-dom';