DEV Community

Cover image for Setting Up Jest in Angular
Elsie
Elsie

Posted on

1 1

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 !

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay