How to use Jest unit tests with Angular

The Jest unit test framework is a relatively new unit testing tool built by Facebook, it is widely used for testing ReactJS projects. Studies shows that Jest is much faster than other unit test frameworks for JavaScript, since it’s using a custom built JavaScript engine instead of running the tests in a full blown browser.

The question is can it also be used for unit tests in an Angular project?
The answer is yes!

Setup the Angular project

So let’s get started, first you need an Angular project that you want to create and run the unit tests for. In this guide we will create the Jest unit tests for the Angular’s Tutorial: Tour of Heroes.

If you want to follow along this guide interactively, you can download the starting point from here:

Unzip it in some folder and run npm install in the folder to get all npm dependencies that you need.

Running the tests with Karma

The project is already shipped with unit tests using Karma. Let’s see if they are working before we convert the project to Jest.
So I started up the tests with command npm run testand noticed that 7 of 8 tests failed. So I had to fix them first before I could even start doing the examples for this story.
You can click here if you are interested in what I fixed in the Karma tests.

Convert the unit test framework to Jest

Now when that is out of the way, we can start the conversion to Jest, start by installing the Jest development dependencies with the command npm install --save-dev jest jest-preset-angular

In src directory create setupJest.ts file with following contents

import 'jest-preset-angular';
import './jestGlobalMocks'; // browser mocks globally available for every test

also create a file jestGlobalMocks.tsin the srcfolder with the following content

and include this in your package.json

"jest": {
  "preset": "jest-preset-angular",
  "setupTestFrameworkScriptFile": "<rootDir>/src/setupJest.ts"

You also need to update the scripts part of the package.json replacing the old test script with the following

"test": "jest",
"test:watch": "jest --watch"

Let’s run the tests now again with Jest in place with command npm run test and for me it all turned green on the first try, very surprising but great!

Click here to see the commit changes I made to configure Jest for Angular.

Check the whole demo project here on GitHub:


Here is a few places where I found the information about using Jest with Angular.

Jest website:


Jest-preset-angular on npm:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at

Up ↑

%d bloggers like this: