DEV Community

Syed Tabarak Ulla
Syed Tabarak Ulla

Posted on • Edited on

Create Angular project with Jest Testing Framework

Image description
STEP:1

npm install -g @angular/cli
Enter fullscreen mode Exit fullscreen mode

STEP:2

ng new my-app-name
Enter fullscreen mode Exit fullscreen mode

STEP:3

cd my-app-name
ng serve --open
Enter fullscreen mode Exit fullscreen mode

STEP:4

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

STEP:5

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

If the above code didn't removed the packages related to Karma and Jasmine, you can remove it manually from the package.json file. And then run the npm install to update the package-lock.json file.

STEP:6
Remove test from the angular.json file

STEP:7
Replace test with jest on the scripts in package.json
"test": "jest",

STEP:8
Create new file as setupJest.ts on root level and add below code in it

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

STEP:9
Remove if these files exist in the project
karma.conf.js and test.ts

STEP:10
Update the types value in the tsconfig.spec.json file

"types": [
      "jest",
      "node"
    ]
Enter fullscreen mode Exit fullscreen mode

STEP:11
Add below code on the package.json

"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

Finally now we can test the application by running the below command on terminal.

npm run test
Enter fullscreen mode Exit fullscreen mode

If you need boilerplate code for Angular app with Jest test framework, please checkout my GitHub repo Angular-with-Jest

Top comments (0)