How to switch from Karma to Jest using Angular

Bruno Picolo
edataconsulting
Published in
7 min readDec 20, 2023

--

Angular comes with Karma by default, but there are a lot of reasons to migrate Karma to Jest. Take a look to this post. Also, Angular is interested in using Jest since v16, so it’s better to get used to Jest 😁

This post is an easy guide to switch from Karma to Jest. As I know some of you might be short on time, I’ll get straight to the point. In the first part I will guide you with the easiest way to setup Jest (Angular v16 and higher). Then, in the second part, there is a similar guide using the older, but still used for Angular v15 and lower, way to migrate Karma to Jest. And finally, in the last part, I’ll explain how Angular 17 test configuration works in more detail.

Do you prefer to read code? Take a look to this Github repo branch. You can follow commit by commit the process to migrate Karma to Jest.

Let’s go!

From Karma to Jest using Angular Jest builder (Angular ≥ v16)

As I mentioned, Angular is working to replace Karma with Jest to make Unit Testing easier. Since Angular v16 we can use an angular jest builder so the ng test command will configure and run jest.

1. Uninstall unneeded deps

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

2. Install Jest Dependencies

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

3. Create the jest.confg.ts

npx jest --init

Answers:

The following questions will help Jest to create a suitable configuration for your project
✔ Would you like to use Jest when running "test" script in "package.json"? … yes
✔ Would you like to use Typescript for the configuration file? … yes
✔ Choose the test environment that will be used for testing › jsdom (browser-like)
✔ Do you want Jest to add coverage reports? … yes
✔ Which provider should be used to instrument code for coverage? › v8
✔ Automatically clear mock calls, instances, contexts and results before every test? … yes

4. Configure the builder adding the following to the angular.json

...
},
"test": {
"builder": "@angular-builders/jest:run",
"options": {
"configPath": "./jest.config.ts"
}
}
...

5. Use the Angular cli for testing

Replace:

"test": "ng test",

With:

"test": "ng test",
"test:watch": "ng test --watch"

6. Running your tests

To run all your tests, use the command npm run test. For interactive execution of tests, use npm run test:watch. This allows for a more dynamic testing experience.

From Karma to Jest without Angular Jest Builder (Angular < v16)

This was the way to migrate from Karma to Jest before the angular Jest Builder.

1. Uninstall unneeded deps

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

2. Clean angular.json file

Remove the test configuration (code extract below) from your angular.json.

,
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}

PS: do not forget the commas!

3. Update test script

Replace:

"test": "ng test",

With:

"test": "jest",

4. Add jest dependencies

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

5. Create the setup-jest.ts

import 'jest-preset-angular/setup-jest';

6. Create the jest.confg.ts

npx jest --init

Answers:

The following questions will help Jest to create a suitable configuration for your project
✔ Would you like to use Jest when running "test" script in "package.json"? … yes
✔ Would you like to use Typescript for the configuration file? … yes
✔ Choose the test environment that will be used for testing › jsdom (browser-like)
✔ Do you want Jest to add coverage reports? … yes
✔ Which provider should be used to instrument code for coverage? › v8
✔ Automatically clear mock calls, instances, contexts and results before every test? … yes

7. Add jest-preset-angular

Add the following to the jest.config.ts file:

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

8. Add the ts-node dependency

npm install ts-node

9. Configure the tsconfig.spec.ts

Update/add the following properties to your tsconfig.spec.ts:

"types": ["jest"], // 1. Register Jest's tye defnition fils with the TS compiler
"esModuleInterop": true, // 2. Avoids anoying warnings [check TS option](https://www.typescriptlang.org/tsconfig#esModuleInterop)
"emitDecoratorMetadata": true // 3. Make Angular's dependency injection work with jest

10. Add test:watch script to package.json

"scripts": {
...,
"test:watch": "jest --watch"
},

11. Running your tests

To run all your tests, use the command npm run test. For interactive execution of tests, use npm run test:watch. This allows for a more dynamic testing experience.

How does the Angular Test Configuration work?

Default Angular Test setup with Karma

  1. npm run test: This command looks into the package.json file of your Angular project to find a script named test.
  2. package.json Test Script: The default test script in an Angular project's package.json usually contains the ng test command.
"scripts": {
"test": "ng test",
// ... other scripts ...
}

3. Angular CLI (ng test): The ng test command is a part of the Angular CLI. When executed, Angular CLI reads the project's angular.json file to find the test configuration.

4. Test Configuration in angular.json: The angular.json file contains configurations for various parts of your Angular application, including the test setup. This configuration specifies the Karma test builder and options for this builder.

"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
// ... options like main test entry file, karma config file, etc. ...
}
}

5. Test Builder: Based on the configuration, the test builder Karma is invoked. Then:

  • Starts a web server to serve the tests.
  • Looks for test entry points (typically src/test.ts) to load test files.
  • Executes the tests found in *.spec.ts files within a browser environment.
  • Reports the results of the tests.

6. Webpack and test.ts: The test.ts file often uses Webpack's require.context to dynamically find and load all *.spec.ts files. This is part of the test execution process managed by Karma.

7. Running Tests and Reporting Results: Karma runs the tests in a browser and reports the results. This can be seen in the console or other configured reporters.

Angular Test setup with Jest

  1. npm run test: This command looks into the package.json file of your Angular project to find a script named test.
  2. package.json Test Script: The default test script in an Angular project's package.json usually contains the ng test command.
"scripts": {
"test": "jest",
// ... other scripts ...
}

3. Jest: The jest command takes over the role of finding the configurations and running the tests.

4. Jest Configuration: The Jest configuration, typically jest.config.js, specifies where to look for test files. By default, Jest looks for files with specific naming patterns like *.spec.ts or *.test.ts.

We could configure Jest using JS, JSON or TS. Because TS has to be transpiled into JS we have to add ts-node as a dependency. Deciding which one to use depends on your project requirements and your personal preferences.

5. jest-preset-angular: The default setup to make Jest work with Angular easily.

To make use of jest-preset-angular, we have to instruct Jest to use it with the preset attribute in the jest.config. This will use a specific set of configurations optimised for Angular applications. Also, we have to apply the jest-preset-angular global configuration before the entire test suite. We apply the preset by referencing the setup-jest.ts in the setupFilesAfterEnv property at the jest.config.

The setup-jest.ts is not only used for applying the jest-preset-angular, it could also include global mocks configuration, setting up global variables, or performing initial setup tasks specific to your application's testing environment.

6. Running Tests and Reporting Results: Jest is already configured at this stage and will run the tests suite.

Angular Test setup with Angular Jest Builder

  1. npm run test: This command looks into the package.json file of your Angular project to find a script named test.
  2. package.json Test Script: The default test script in an Angular project's package.json usually contains the ng test command.
"scripts": {
"test": "ng test",
// ... other scripts ...
}

3. Angular CLI (ng test): The ng test command is a part of the Angular CLI. When executed, Angular CLI reads the project's angular.json file to find the test configuration.

4. Test Configuration in angular.json: The angular.json file contains configurations for various parts of your Angular application, including the test setup. This configuration specifies the Jest test builder and options for this builder.

"test": {
"builder": "@angular-builders/jest",
"options": {
// ... options like main test entry file, karma config file, etc. ...
}
}

5. Jest Test Builder: Based on the configuration, the test builder is invoked. Jest then:

  • Configures Jest to work with Angular using angular-jest-preset
  • Executes the tests found in *.spec.ts files within a browser environment.
  • Reports the results of the tests.

6. Running Tests and Reporting Results: Jest runs the tests in the terminal and reports the results.

The Angular Jest builder make the test configuration easier, we do not need anymore to take care about the jest-preset-angular. Also, because we are using an angular builder the steps are similar to other builders like Karma.

Some Interesting metrics

  • Karma vs Jest pros and cons comparison. It would be also great to have a Karma vs Jest performance review, but I haven’t found any. If you’re interested on performance, record your project performance running Karma follow these Karma to Jest migration steps and record Jest performance.
  • Karma vs Jest NPM trends. This shows how Jest is more popular than Karma. It’s an interesting metric to deciding to switch to Jest because bugs will be solved faster and features will come faster as well.

Summary

Angular testing is moving towards using Jest instead of Karma, and it’s important for us to update our projects to keep up with this change. In the first and second part of this article, we showed two easy ways to switch from Karma to Jest for Angular apps, the first one for Angular for newer Angular versions (>v16) and the second for older versions. Then, in the last part, we compared how Angular works with both Karma and Jest. We also explained the purpose of different configuration files and their roles. This will give you a clearer understanding of how testing is done in Angular, making it easier for you to adapt to these changes.

We at edataconsulting regularly handle these software challenges. Take a look at our website to know more about us.

--

--