Setting Up Jest in Your Angular Project

Philip Mutua
6 min readJan 22, 2024

Testing lies at the heart of building robust and reliable Angular applications. In this blog, we’ll embark on a journey to harness the power of Jest, a potent testing framework, coupled with jest-preset-angular, to elevate your testing experience in Angular projects. Let's dive in and explore how you can unlock the full potential of testing within your Angular applications.

Step 1: Create Your Angular Project

If you haven’t already, use the Angular CLI to create a new Angular project:

ng new your-angular-project
cd your-angular-project

Step 2: Uninstall all karma jasmine package

Go to the Package.json file and remove all these packages

  "devDependencies": {
"@angular-devkit/build-angular": "^14.2.13",
"@angular/cli": "~14.2.13",
"@angular/compiler-cli": "^14.2.0",
"@types/jasmine": "~4.0.0", // remove
"jasmine-core": "~4.3.0", // remove
"karma": "~6.4.0", // remove
"karma-chrome-launcher": "~3.1.0", // remove
"karma-coverage": "~2.2.0", // remove
"karma-jasmine": "~5.1.0", // remove
"karma-jasmine-html-reporter": "~2.0.0", // remove
"typescript": "~4.7.2"
}js

Command to remove karma and jasmine packages

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

Step 3: Remove the test object from angular.json

{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"jest-setup-project": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/jest-setup-project",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "jest-setup-project:build:production"
},
"development": {
"browserTarget": "jest-setup-project:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "jest-setup-project:build"
}
},
//REMOVE THIS TEST OBJECT BELOW
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
// Delete Above test object
}
}
}

Step 4: Delete karma.config.js file and test.ts file

In your angular application locate the karma.config.js file your angular project has these two files delete them.

Setting the Stage: Installing Dependencies

To kickstart your enhanced testing experience, begin by installing the required dependencies using your preferred package manager

# Using Yarn
yarn add -D jest jest-preset-angular @types/jest

# Using npm
npm install -D jest jest-preset-angular @types/jest

This step lays the foundation for Jest and configures it seamlessly with jest-preset-angular. With the dependencies in place, let's proceed to set up Jest for your Angular project.

You might get the following error when installing:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: jest-setup-project@0.0.0
npm ERR! Found: @angular-devkit/build-angular@14.2.13
npm ERR! node_modules/@angular-devkit/build-angular
npm ERR! dev @angular-devkit/build-angular@"^14.2.13" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular-devkit/build-angular@">=15.0.0 <18.0.0" from jest-preset-angular@14.0.0
npm ERR! node_modules/jest-preset-angular
npm ERR! dev jest-preset-angular@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:\Users\userx\AppData\Local\npm-cache\_logs\2024-01-22T07_25_26_571Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: C:\Users\Philip.Mutua\AppData\Local\npm-cache\_logs\2024-01-22T07_25_26_571Z-debug-0.log

To fix the error you must run the following command:

npm install -D jest jest-preset-angular @types/jest --legacy-peer-deps

Explanation:

--legacy-peer-deps: This flag is used to enable support for installing packages that declare peer dependencies without explicitly listing them in their package.json files. It is often used when working with older packages that haven't been updated to support the stricter peer dependency rules introduced in newer versions of npm.

OR

OR 

npm install -D jest jest-preset-angular @types/jest --force

Explanation:

--force: This flag is used to force the installation of the specified packages, even if it might lead to conflicts or other issues.

Creating a Jest Setup File

Create a setup-jest.ts file in the src folder src/setup-jest.ts. This file will serve as the setup script for Jest:

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

This file ensures that Jest is properly configured for your Angular project. Now, let’s integrate Jest into your project by updating the configuration.

Step 8: Add configuration in package.json

Add the configuration in your package.json file:

  "jest": {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
"<rootDir>/src/setup.jest.ts"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"globals": {
"ts-jest": {
"tsConfig": "<rootDir>/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$"
}
}
}

With these configurations in place, Jest becomes seamlessly integrated into your Angular project.

Example of package.json File

{
"name": "jest-setup-project",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "jest" // NEW UPDATE
},
// NEW UPDATE
"jest": {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
"<rootDir>/src/setup-jest.ts"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"globals": {
"ts-jest": {
"tsConfig": "<rootDir>/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$"
}
}
},
"private": true,
"dependencies": {
"@angular/animations": "^14.2.0",
"@angular/common": "^14.2.0",
"@angular/compiler": "^14.2.0",
"@angular/core": "^14.2.0",
"@angular/forms": "^14.2.0",
"@angular/platform-browser": "^14.2.0",
"@angular/platform-browser-dynamic": "^14.2.0",
"@angular/router": "^14.2.0",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
.........

Make sure you also change the “scripts” test command to as follows:

  "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "jest", // change here to this
"test:watch": "jest --watch", // New (optional)
"test:coverage": "jest --coverage" // new (optional)
},
.......

TypeScript Configuration

Update your tsconfig.spec.json file to ensure compatibility:

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest" // New
]
},
"files": [
"src/test.ts", // REMOVE THIS
"src/setup-jest.ts", // NEW Add this so that the file will be found
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

It’s crucial to note that Angular doesn’t support native async/await in testing with a target higher than ES2016. Refer to this issue for further details.

Once you’ve set up Jest in your Angular project using jest-preset-angular, running Jest tests is a straightforward process. Follow these steps to execute your Jest tests:

Open your terminal

Open your terminal or command prompt. Ensure that you are in the root directory of your Angular project.

Run Jest

Use the following command to run Jest tests:

npm run test

This command will initiate Jest and execute your tests. Jest will look for test files matching the pattern specified in your Jest configuration (usually files with a .spec.ts extension).

Test Results

Observe the Results: Jest will run your tests and provide detailed feedback in the terminal. You’ll see information about test suites, individual test cases, and the overall test results.

  • Green Checkmarks: Indicates passed tests.
  • Red Crosses: Indicates failed tests.

Additionally, Jest may generate a coverage report, depending on your configuration. You can find the coverage report in the specified directory (e.g., coverage/your-angular-project).

You can find the repository link here

Delve Deeper into the Jest Universe

For a deeper understanding and continuous updates, check out our online documentation. Immerse yourself in the world of testing Angular faster and with confidence using Jest and jest-preset-angular. Happy testing!

--

--