Jest Integration with Angular 12
Let’s start!
By default, Angular is using jasmine and karma for unit testing. Here we have tried to integrate jest with the angular project for lightweight unit testing.
1. Manage dependencies
- First, uninstall all karma-related devDependencies. You can use the below command to uninstall those devDependencies.
npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
- Then install jest-related devDependencies as below.
npm install jest @types/jest jest-junit jest-preset-angular ts-jest — save-dev
2. Remove and update jsons
- Remove test object from angular.json
- Update scripts section in package.json as below
3. Remove and update config files
- Delete karma.conf.js from the root level of the project
- Create and update jest.config.js at the root level of the project
- Delete test.ts from the src directory
- Create and update setupJest.ts in the src directory
4. Remove and update tsconfig jsons
- Update tsconfig.json like below
- Update tsconfig.spec.json like below
4. Run and check unit testing
- Run the below script in the terminal to check
npm run test
- Run the below script to test your changes in watch mode
npm run test:watch
- Run the below script to see coverage of a single component as well as the complete application
npm run test:coverage
Note: At the root level of the project, the coverage directory will be created and if we open index.html in the browser, we can see code coverage of the complete application. (Path: jest-ng-seed/coverage/jest-ng-seed/lcov-report/index.html)
Please find the below GitHub link for above code snippets and the seed project named jest-ng-seed.
Summary
We have explored jest integration with Angular 12 in detail with one seed project named jest-ng-seed.
Happy Coding!!