Karma is deprecated, and the Angular team is working on official support for Jest and Web Test Runner. Today, I want to highlight how to set up your Angular project for Jest since it’s prevalent in the Javascript ecosystem (React, etc.). It’s super fast and 100% browserless, making running tests on a continuous integration server easy.
Also, the syntax is essentially the same as Jasmine/Karma, so you won’t have to change your tests much unless you do extensive mocking in Jasmine.
Here are the steps I’ve used on over 28 repositories so far, with great success:
- Uninstall Jasmine, Karma, and all associated types
npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter @types/jasmine jasmine-core
- Install Jest, its types, and presets for Angular
npm i --save-dev jest @types/jest jest-preset-angular
- Create a
setup-jest.ts
file in your project’s root folder
And add that single line of code in it:import 'jest-preset-angular/setup-jest';
- Create a
jest.config.ts
file in your project’s root folder with the following commandnpx jest — init
Then ensure you have the following config options set in that file:preset: 'jest-preset-angular',
setupFilesAfterEnv: ['./setup-jest.ts'] - Update your
tsconfig.spec.json
file
YourcompilerOptions
should look like this:"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [ "jest" ],
"esModuleInterop": true,
"emitDecoratorMetadata": true
}, - Last step: Update
package.json
In the scripts section, replace thetest
entry with:"test": "jest",
And… that’s it! You can now launch npm run test
to run your tests with Jest. Sure, a schematic would be better, but those steps take only 2-3 minutes to implement for now.