DEV Community

Fran Saoco
Fran Saoco

Posted on • Edited on

5 1

How to Set Up Jest in Angular 19 (Step-by-Step Guide)

1. Install the dependencies:

npm install jest jest-preset-angular @types/jest --save-dev
Enter fullscreen mode Exit fullscreen mode
  • jest: Core testing framework.
  • jest-preset-angular: Adds Angular support for Jest.
  • @types/jest: TypeScript definitions for Jest.

2. Remove Karma:

npm remove karma karma-chrome-launcher karma-jasmine karma-coverage karma-jasmine-html-reporter
Enter fullscreen mode Exit fullscreen mode

3. Update test script on package.json file:

"scripts": {
    ...
    "test": "jest",
Enter fullscreen mode Exit fullscreen mode

4. Create jest.config.js file:

module.exports = {
    preset: 'jest-preset-angular',
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
    testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'],
    transform: {
        '^.+\\.ts$': 'ts-jest', // Only transform .ts files
    },
    transformIgnorePatterns: [
        '/node_modules/(?!flat)/', // Exclude modules except 'flat' from transformation
    ],
};
Enter fullscreen mode Exit fullscreen mode

5. Create setup-jest.ts file:

import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
setupZoneTestEnv();
Enter fullscreen mode Exit fullscreen mode

6. Update tsconfig.spec.json file:

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

7. Update the test property in angular.json file:

"test": {
  "builder": "@angular-devkit/build-angular:jest",
  "options": {
    "tsConfig": "tsconfig.spec.json"
  }
}
Enter fullscreen mode Exit fullscreen mode

8. Verify that esModuleInterop property is included in tsconfig.json file:

"compilerOptions": {
    "baseUrl": "./",
    ...
    "esModuleInterop": true, // <= add it if it is not there
Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (2)

Collapse
 
xample profile image
Flavien Volken

Update test script on angularpackage.json file

Collapse
 
fransaoco profile image
Fran Saoco

Yes! updated, thanks!

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay