Angular Unit Testing with Jest

Here in this article I am going to show you an example on Angular unit testing with Jest.

While Karma has been the default testing framework for Angular in the past until the Angular version 16. In Angular 16, the karma has been deprecated and jest has been introduced in the experimental mode. Jest is being explored as a potential replacement due to its simplicity, speed and built-in features like snapshot testing and mocking.

While it is in experimental mode in Angular, you should note that using it in production environment may have limitations or unsupported features.

Jest being the popular testing framework from Facebook, it is widely used mainly in the React applications. It provides everything needed for unit testing for JavaScript applications, including powerful mocking, built-in assertions, code coverage, and headless testing with JSDOM. It provides faster execution compared to Karma and Jasmine, and hence it provides better developers’ experience.

Jest setup in Angular

Create New Project

Create a new Angular project using the following command:

ng new angular-jest-unit-test --no-standalone

Uninstall karma and jasmine packages

By default karma and jasmine are included in the angular project and it’s included when you create a new Angular project. So, you need to remove the karma and jasmine packages from your Angular project as you are going to use jest for unit testing.

Use the below command to remove the packages:

npm uninstall karma karma-jasmine karma-chrome-launcher karma-coverage karma-coverage-istanbul-reporter karma-jasmine-html-reporter jasmine-core jasmine-spec-reporter @types/jasmine @types/jasminewd2

Install jest package

Once you successfully remove the karma and jasmine packages, install the jest package by executing the following command:

npm install jest jest-preset-angular @types/jest --save-dev

The @types/jest package provides type declaration files for the Jest, enabling TypeScript to perform type checking and provide IntelliSense support for Jest-specific APIs, functions, and matchers.

The jest-preset-angular package is a crucial tool for running Angular unit tests with Jest. It provides the following features:

ts-jest: A library included in @types/jest that allows Jest to trans-compile TypeScript code in-memory, facilitating seamless integration between TypeScript and Jest during testing.

Snapshot serializers: @types/jest provides specialized serializers for Angular components, enhancing snapshot testing capabilities by enabling easy comparison and validation of component snapshots.

AST transformers: The included AST transformers in @types/jest modify Angular component code during testing, removing CSS styles and inline HTML templates. This ensures compatibility with JSDOM, enabling headless testing without relying on external resources.

Create setup-jest.ts file in root folder

In the Angular project’s root folder create setup-jest.ts file and import the package and setup zone test environment.

import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';

setupZoneTestEnv();

Create jest.config file

You need to create jest.config file to put various configurations for jest framework. You can use the following command to create the jest config file:

npx jest --init

The npx jest --init command initializes Jest in your project by creating a jest.config.js / jest.config.ts file and providing a guided setup process.

You need to input yes or value for the questions asked during setup and creation of the file. You can use up or down arrow for few questions to select the appropriate values.

angular jest unit test

Set preset and setupFilesAfterEnv value in jest.config.ts file as mentioned below:

preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],

It is required to install ts-node for the TypeScript configuration files using the following command:

npm i ts-node

ts-node provides a convenient way to execute TypeScript files and experiment with TypeScript code interactively.

Update tsconfig.spec.json file

Register jest’s type definitions files with the TypeScript compiler.

Enable the esModuleInterop option of the TypeScript compiler otherwise jest will output a lot of warnings in the console.

Enable the emitDecoratorMetadata option of the TypeScript compiler otherwise Angular’s Dependency Injection won’t work with jest.

Update tsconfig.spec.json file as below:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jest"
    ],
    "esModuleInterop": true,
    "emitDecoratorMetadata": true
  },
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

Running test

You can use any one of the commands to execute the test: npm run test or npx jest or npm run test:coverage

Once the test file is run, you will see the following output:

angular jest unit test

If you see the following warning during unit test execution:

DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.

You can upgrade your nodejs version to 22.14.0 or higher to fix the issue.

Source Code

Download

Share

No comments

Leave a comment