Install Jest for Angular
A powerful combination, you should try it
Hey you know we all desire to work with the best libraries. For months, I only use Jest in my Angular projects. It’s faster, less unexpected behaviors and it offers the snapshot feature which is really a must-have.
Try it yourself, you will see that you will leave Karma/Jasmine for it.
Get Redin Gaetan’s stories in your inbox
Join Medium for free to get updates from this writer.
Angular 12.2 / Jest 27.2.0
Step 1: Just install the essential
npm install jest jest-preset-angular --save-devStep 2: Create a small setup file
cd src
touch setupJest.tsStep 3: Add only this as config
// setupJest.ts
import 'jest-preset-angular/setup-jest';Step 4: Add entry to the package.json
// package.json
{
...
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/setupJest.ts"
}
...
}Step 5: Replace the test(s) script(s)
// package.json
"test": "jest",
"test:watch": "jest --watch",
"test:ci": "jest --runInBand"Step 6: Uninstall Karma/Jasmine
npm uninstall karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporterStep 7: Remove useless files
You can now remove the karma.conf.js and test.ts files.
Step 8: Test it
npm run test> XXX@0.0.0 test <my-project-path>
> jestPASS src/app/app.component.spec.ts
AppComponent
√ setup (2 ms)Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.069 s
Ran all test suites.
The function API is almost the same so you will not be disoriented. Just take time to understand the snapshot feature.
Tips
Config file paths
You can get this:
Cannot find module 'src/**' from 'src/**.spec.ts'To avoid this, you juste have to add this into your config:
"jest": {
...
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/src/$1"
},
...
},Thanks for reading. Feel free to comment.








