Integrating Jest with latest angular version

As jest is increasingly gaining traction in unit testing angular components lets see how to integrate it with latest angular versions (12+)

  • uninstall jasmine & karma using npm uninstall -D @types/jasmine jasmine jasmine-core jasmine-spec-reporter karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter ts-node

  • install jest using npm i -D @types/jest jest jest-preset-angular @angular-builders/jest

  • create file setupJest.ts in root and add below content

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import 'jest-preset-angular';
import 'zone.js';
import 'zone.js/testing';

getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
  {
    teardown: { destroyAfterEach: true },
  }
);

Object.defineProperty(window, 'CSS', { value: null });
Object.defineProperty(window, 'getComputedStyle', {
  value: () => {
    return {
      display: 'none',
      appearance: ['-webkit-appearance']
    };
  }
});
Object.defineProperty(document, 'doctype', {
  value: '<!DOCTYPE html>'
});
Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true
    };
  }
});
  • If you are migrating from lower angular version using ng upgrade then except above piece of code if you are using any other piece of code in src/test.ts file then add that new content to setupJest.ts and delete src/test.ts

  • create file jest.config.js in root and add below content

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  collectCoverage: true,
  coverageReporters: ['html', 'lcov', 'json', 'text'],
  coverageDirectory: '<rootDir>/coverage',
  moduleFileExtensions: ['ts', 'html', 'js', 'json'],
};
  • replace test part of angular.json with below content
...
"test": {
  "builder": "@angular-builders/jest:run",
  "options": {
    "main": ["setupJest.ts"],
    "tsConfig": "src/tsconfig.spec.json",
    "no-cache": true
  }
}
...
  • add "esModuleInterop": true to compilerOptions in tsconfig.json
  • open tsconfig.spec.json and replace jasmine with jest in types field

That's it jest is now comlpetely integrated with latest angular 👏 💥

Thanks for reading 👍 and post any issue if you faced while doing so in comments below 👇

You can find the example repo here

30