Angular 11 - Setting up Jest

alfredoperez

Alfredo Perez

Posted on July 6, 2020

Angular 11 - Setting up Jest

This is a quick guide to setup Jest in your new Angular 10 application

1. Install Jest

npm install jest @types/jest jest-preset-angular --save-dev
Enter fullscreen mode Exit fullscreen mode

2. Uninstall Karma

npm uninstall karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter @types/jasmine @types/jasminewd2 jasmine-core jasmine-spec-reporter
Enter fullscreen mode Exit fullscreen mode

3. Remove test from angular.json

Remove the test section from angular.json, this section looks like the following:

   "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
Enter fullscreen mode Exit fullscreen mode

4. Remove karma.conf.js and src/test.ts files

5. Create setupJest.ts file

This file should have the following:

import 'jest-preset-angular';
Enter fullscreen mode Exit fullscreen mode

6. Modify tsconfig.spec.json

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

7. Modify package.json file

Modify the test scripts to the following:

 "test": "jest",
 "test:coverage": "jest --coverage",
Enter fullscreen mode Exit fullscreen mode

Add Jest configuration to the end of this file:

"jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": [
      "<rootDir>/setupJest.ts"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/node_modules/",
      "<rootDir>/dist/"
    ],
    "globals": {
      "ts-jest": {
        "tsConfig": "<rootDir>/tsconfig.spec.json",
        "stringifyContentPathRegex": "\\.html$"
      }
    }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
alfredoperez
Alfredo Perez

Posted on July 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Angular 11 - Setting up Jest
angular Angular 11 - Setting up Jest

July 6, 2020