DEV Community

Cover image for Angular 6: “ng test” with Jest in 3 minutes
JeB
JeB

Posted on • Updated on

Angular 6: “ng test” with Jest in 3 minutes

Hey folks.

Today I’m going to show you how to setup your Angular CLI workspace to work with Jest while keeping it clear of boilerplate code.

I'm not going to explain why you should choose Jest over Karma, assuming you already did that choice, however I will give you a link to an article that explains the reasons.

So let’s get started!

Setting up Jest

Remove Karma related stuff:

npm remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
rm src/karma.conf.js src/test.ts

Install @angular-builders/jest and jest:

npm i -D jest @angular-builders/jest

Update your Typescript configurations:

Although you run your unit tests with Jest, Protractor (e2e tests) still has to use Jasmine. Due to this fact it’s possible that you favorite IDE will get confused with the typings and will propose you Jasmine types in unit tests or Jest types in e2e test. In order to avoid that kind of problems you have to specify the types explicitly:

In tsconfig.spec.json (src directory or project roots, used by Jest):

"compilerOptions": {
 ...
 "module": "commonjs",
 "types": ["jest"]
}

In tsconfig.json (root directory, used by IDE):

"compilerOptions": {
    ...
    "types": ["jest"]
}

In angular.json change @angular-devkit/build-angular:karma to @angular-builders/jest:run:

"projects": {
    ...
    "[your-project]": {
         ...
         "architect": {
                ...
                "test": {
                          "builder": "@angular-builders/jest:run"
                          "options": {
                                ...// see below
                          }

Detailed description of options object can be found here.

This is it, now you can run your tests with Jest.

Running the tests with Jest

  • To run tests for all the projects in workspace: ng test
  • To run tests for a specific project my-project: ng test my-project
  • You can specify Jest CLI options either in builder options (useful when it is a persistent config) or right to ng test as a parameter (useful when it is a one-timer).  For example to run a single test:  ng test --testNamePattern="My test suite My test case"

Further reading

If you’d like to learn more about builders and even considering creating one of your own check out this article.

Discussion (0)