Setup Jest on your Angular Application

By default Angular comes with Karma as test runner and Jasmine as test framework.The tests are running in Chrome. Running unit tests in Chrome is not feasible on a CI/CD pipeline - but you can install and use ChromeHeadless (with --no-sandbox flag) and puppeteer.

But what if we can run unit tests without a real browser? This should improve the running time and the stability but also the node_modules size. It's easy to achieve this with Jest. Jest is a complete test framework (code coverage, easy mocking etc.) which by default runs in jsdom.

Most part of the syntax is similar to Jasmine. The main difference is how you mock / spy a function, so you need to update your unit tests to support it.

Steps to integrate Jest

Please note that the following commands may need small adjustments based on your application folder structure.

Remove karma and jasmine

>> npm uninstall karma karma-chrome-launcher karma-cli karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter karma-typescript @types/jasmine jasmine-core jasmine-spec-reporter jasmine-allure-reporter @types/jasminewd2

>> rm karma.conf.js

>> rm src/test.ts

Add Jest packages

>> npm install --save-dev @types/jest jest jest-preset-angular @angular-builders/jest

Jest configurations files

jest.setup.ts

import 'jest-preset-angular';

jest.config.js

module.exports = {
  preset: 'jest-preset-angular',
  
  globals: {
    'ts-jest': {
      tsConfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.html$',
      astTransformers: [
        'jest-preset-angular/build/InlineFilesTransformer',
        'jest-preset-angular/build/StripStylesTransformer'
      ],
      isolatedModules: true // mandatory for a boost of perfomance
    }
  },
  setupFilesAfterEnv: ["jest.setup.ts"],
  roots: ['your-root-dir']
  moduleNameMapper: { 'your-custom-mappings' } // optional
}

Update angular.json to support ng test

... {
  "test": {
    "builder": "",
    "options": {
      "configPath": "jest.config.js",
      "rootDir": "your-rootdir"
    }
  }
}

Update tsconfig.spec.json

"compilerOptions": {
  "outDir": "./out-tsc/spec",
  "module": "commonjs",
  "types": ["jest", "node"],
  "emitDecoratorMetadata": true, // make sure this is on
  "allowJs": true,

  "sourceMap": false
}

To view or add a comment, sign in

More articles by Cosmin Bondane

  • Performance tuning - C# Dapper and SQL char

    In this post I will explain how a simple SQL query executed with Dapper can lead to performance issues and how I…

    1 Comment

Explore content categories