Gilles Ferrand
Gilles' Journey

Follow

Gilles' Journey

Follow
How to install Jest in Angular 13

How to install Jest in Angular 13

Today we will see how to install Jest in an Angular project

Gilles Ferrand's photo
Gilles Ferrand
·Jan 7, 2023·

2 min read

Table of contents

  • Jest

Jest

When you generate a new Angular project, it comes with some tools for unit testing, Karma and Jasmine

Sometimes you need to replace theses tools with another framework like Jest

What is Jest ?

Jest is a testing framework developed by Facebook, it is very popular for unit testing in React. It comes with a lot of tools :

  • Mocking tools

  • Assertions tools

  • Code coverage

  • JSDOM library to allow Jest to run outside a browser, it is very useful to run test on CI

  • Watch mode to re-run only affected tests ...

Why Jest instead of Karma and Jasmine

We like to use Jest instead of Karma and Jasime because it can run without a browser, and it can run easily on CI. Also Jest is way faster than Karma, it's well documented, you can run only affected tests...

Jest can come with @types/jest package which contains type declaration, useful for type checking for example

Jest Preset Angular

jest-preset-angular is Jest preset configuration and TypeScript preprocessor with source map support for Jest that lets you use Jest to test Angular projects.

Installation

To install jest-preset-angular and dependencies all at once you can use

with npm npm install -D jest jest-preset-angular @types/jest or with yarn yarn add -D jest jest-preset-angular @types/jest

Configuration

In your project root create a file setup-jest.ts

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

and a file jest.config.js

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

Edit your tsconfig.spec.json like this { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "module": "CommonJs", "types": ["jest"] }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] } Edit your package.json ... "watch": "jest --watch", "test": "jest" ...

You can now run test with npm run test

Clean up Karma and Jasmine

You can now remova Karma and Jasmine from your project

Delete src/test.js

Delete in angular.json

        "test": {
          ...
        }

Run in terminal this command to clean up all dependencies

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

or

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

Sources :

https://www.xfive.co/blog/testing-angular-faster-jest/

https://thymikee.github.io/jest-preset-angular/docs/

 
Share this