
Angular CLI: “ng test” with Jest in 3 minutes

Update:
The article is relevant for Angular <8.
Find the updated version of this article here.
This and other articles are available for free on my personal blog. Make sure to sign up to get the latest and greatest!
Hey folks.
Today I’m going to show you how to setup your Angular CLI workspace to work with Jest while keeping it clear of boilerplate code.
I’m not going to explain why you should choose Jest over Karma, assuming you already did that choice, however I will give you a link to an article that explains the reasons.
So let’s get started!
Setting up Jest
- Remove Karma related stuff:
npm remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporterrm src/karma.conf.js src/test.ts
2. Install @angular-builders/jest
and jest
:
npm i -D jest @types/jest @angular-builders/jest@7.x.x
Note: for Jest 23 use version 7.3.x of angular-builders/jest
.
3. Update your Typescript configurations:
Although you run your unit tests with Jest, Protractor (e2e tests) still has to use Jasmine. Due to this fact it’s possible that you favorite IDE will get confused with the typings and will propose you Jasmine types in unit tests or Jest types in e2e test. In order to avoid that kind of problems you have to specify the types explicitly:
In tsconfig.spec.json (src directory or project roots, used by Jest):
"compilerOptions": {
...
"module": "commonjs",
"types": ["jest"]
}
You also should remove test.ts
from files
array.
In tsconfig.json (root directory, used by IDE):
"compilerOptions": {
...
"types": ["jest"]
}
4. In angular.json change @angular-devkit/build-angular:karma
to @angular-builders/jest:run
:
"projects": {
...
"[your-project]": {
...
"architect": {
...
"test": {
"builder": "@angular-builders/jest:run"
"options": {
... //see here
}
This is it, now you can run your tests with Jest.
Running the tests with Jest
- To run tests for all the projects in workspace:
ng test
- To run tests for a specific project my-project:
ng test my-project
- You can specify Jest CLI options either in builder options (useful when it is a persistent config) or right to
ng test
as a parameter (useful when it is a one-timer).
For example to run a single test:ng test --testNamePattern="My test suite My test case"
Further reading
If you’d like to learn more about builders and even considering creating one of your own check out this article.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.