shou2017.com
JP

Introducing Jest into Angular

Sun May 18, 2025
Sun May 18, 2025

Environment

  • Angular 19
  • node.js 22

Introduction

Angular testing used to be done with Karma, but it is now deprecated and Web Test Runner, Vitest, and Jest are recommended. This is also mentioned in the roadmap.

Angular Roadmap

So, I thought that from version 19 it would be easy to introduce Jest or Vitest, but Karma was still included by default. Therefore, if you want to migrate from Karma to another test framework, you have to do it yourself.

This time, I’ll leave a memo on how to introduce Jest.

Removing Karma

Remove Karma and related packages.

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

Installing Jest

Install Jest and related packages.

npm install --save-dev \
  jest \
  @types/jest \
  ts-jest \
  jest-environment-jsdom 

Modifying angular.json

Change the test configuration in angular.json to @angular-devkit/build-angular:jest.

"test": {
  "builder": "@angular-devkit/build-angular:jest",
    "options": {
      "polyfills": [
        "zone.js",
        "zone.js/testing"
       ],
      "tsConfig": "tsconfig.spec.json"
    }
}

Modifying tsconfig.spec.json

By default, the types in compilerOptions are set to jasmine, so change them to Jest.

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

Also modify tsconfig.json.

# tsconfig.json
"compilerOptions": {
	"outDir": "./dist/out-tsc",
	"strict": true,
	"noImplicitOverride": true,
	"noPropertyAccessFromIndexSignature": true,
	"noImplicitReturns": true,
	"noFallthroughCasesInSwitch": true,
	"skipLibCheck": true,
	"isolatedModules": true,
	"esModuleInterop": true,
	"experimentalDecorators": true,
	"moduleResolution": "bundler",
	"importHelpers": true,
	"target": "ES2022",
	"module": "ES2022",
	"types": ["./worker-configuration.d.ts", "node", "jest"]
},

Run

Once all the settings are done, let’s run the tests.

npx ng test

The tests will run and Jest’s results will be displayed. There may be some errors, but the introduction of Jest was successful.

Test Suites: 1 failed, 2 passed, 3 total
Tests:       2 failed, 3 passed, 5 total
Snapshots:   0 total
Time:        0.628 s

That’s it for migrating to Jest. It was pretty easy. It’s still unclear which test framework will be officially supported by Angular, but I hope they decide soon。

Tags
Jest
See Also