DEV Community

Cover image for Setting Up Jest in Angular
Elsie
Elsie

Posted on

Setting Up Jest in Angular

Install Jest in dev dependencies:
npm install --save-dev jest jest-preset-angular @types/
jest
Enter fullscreen mode Exit fullscreen mode
Uninstall Karma in default Angular project
npm uninstall karma karma-chrome-launcher karma-jasmine-html-reporter @types/jasmine @types/jasminewd2 jasmine-core jasmine-spec-reporter karma-coverage-istanbul-reporter karma-jasmine
Enter fullscreen mode Exit fullscreen mode

Note: also delete karma.conf.js & src/test.ts from project

Update the test configuration angular.json file:
{
 ...
 ...
 "test": {
    "builder": "@angular-builders/jest:run",
    "options": {
      "tsConfig": "<rootDir>/src/tsconfig.test.json",
      "collectCoverage": false,
      "forceExit": true
    }
 },
 "lint": {...},
 "e2e": {...}
 ...
}
Enter fullscreen mode Exit fullscreen mode
Create file name jestSetup.ts

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

Update tsconfig.spec.json
"compilerOptions": {
 "outDir": "./out-tsc/spec",
 "types": ["jest", "node"],
 "esModuleInterop": true,
 "emitDecoratorMetadata": true
 },
Enter fullscreen mode Exit fullscreen mode
Update package.json run script
"test": "jest",
"test:coverage": "jest --coverage",
Enter fullscreen mode Exit fullscreen mode
Add Jest configuration in package.json
"jest": {
 "preset": "jest-preset-angular",
 "setupFilesAfterEnv": [
 "<rootDir>/jestSetup.ts"
 ],
 "testPathIgnorePatterns": [
 "<rootDir>/node_modules/",
 "<rootDir>/dist/"
 ],
 "globals": {
   "ts-jest": {
     "tsconfig": "<rootDir>/tsconfig.spec.json",
     "stringifyContentPathRegex": "\\.html$"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Finally, run with command
npm run test to check your result

Happy Coding !

Top comments (0)