Using Jest for Testing in an Angular Project

Jest is a popular testing framework, but, unfortunately, it does not come with a new Angular project out of the box. In this article, we will go over how to quickly replace Karma and Jasmine, the default test runner and assertion framework in a new Angular project, with Jest.

Prerequisites

This article assumes you have Node and NPM configured for your development environment and have the Angular CLI tool installed.

Create a New Angular Project

We will start by using the Angular CLI to generate a new Angular project: ng new angular-and-jest

The CLI will prompt you with a few questions. You can choose the options best for you or your project because they won’t affect the rest of our setup.

After the project generation is complete, we can run ng test to ensure everything was created successfully.

Remove Karma and Jasmine

>Next, we will remove some boilerplate for Karma and Jasmine that we no longer need. We can start with removing the NPM packages:

npm remove @types/jasmine jasmine-core karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter

We can now delete the files /src/test.ts and karma.conf.js and remove the reference to test.ts in the files array in tsconfig.spec.json. While we have our tsconfig.spec.json file open, we can also replace jasmine with jest in the types array. Lastly, add emitDecoratorMetadata to the compilerOptions.

When you’re done, your tsconfig.spec.json file should look like this:

Use Jest to Replace Default Test Runners in an Angular Project

Add Jest Dependencies and Configuration

Now we can add Jest and a few other dependencies to our project:

npm i @angular-builders/jest @types/jest jest --save-dev

Next, we can update our angular.json file so that we can continue to use the ng test command to run our tests. Replace the following line "builder": "@angular-devkit/build-angular:karma" in the test node with "builder": "@angular-builders/jest:run". We can delete the lines "main": "src/test.ts" and "karmaConfig": "karma.conf.js", which were needed to configure Karma. Lastly, we need to convert the polyfills and inlineStyleLanguge nodes to be arrays of strings instead of a single string.

When you’re done, your test node should look like this:

Running Tests with Jest

We have everything configured to run our tests with Jest! Run the ng test command to see the results.

Conversation
  • Elaine says:

    Love this post, Rob!

  • Join the conversation

    Your email address will not be published. Required fields are marked *