Angular with Jest setup

In this article, I'll show how to set up a basic Angular app with Jest. In case of any problems please refer to the official documentation:

The setup is based on Angular 15 and Jest 29. Make sure you have globally installed Angular CLI 15 and npx.

Create the app (optional)

Create the new application with the defaults using Angular CLI.

ng new app --defaults=true

Navigate to the app directory:

cd app

Set up the Jest

Install required dependencies

npm i jest@29 @types/jest@29 jest-preset-angular ts-jest

Create setup-jest.ts file the application root and insert contents:

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

Create jest.config.js file in the application root and insert contents:

module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
};

Update tsconfig.spec.json file to match the following contents. There are two differences between the original and the changed file:

  • added "module": "CommonJs"

  • changed "types": ["jasmine"] to "types": ["jest"]

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

Remove karma and jasmine dependencies.

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

Verify

Use the following command to run the tests. In the default app, there is one test suite for the AppComponent with 3 tests.

npx jest

The tests were run successfully.

 PASS  src/app/app.component.spec.ts
  AppComponent
    ✓ should create the app (183 ms)
    ✓ should have as title 'app' (36 ms)
    ✓ should render title (34 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.577 s, estimated 5 s
Ran all test suites.