ilancohen
ilancohen

Reputation: 89

Can I run Jest through the Angular CLI?

I have configured my Angular 6 application to run tests with Jest when I run "npm run test". This works fine. I'd like to be able to run those same tests when I execute "ng test". Is it possible to configure the Angular CLI to do this?

Upvotes: 3

Views: 2612

Answers (1)

hoefling
hoefling

Reputation: 66261

I really recommend using the Jest builder if you want to switch to Jest in your Angular CLI project. We just had a migration from Karma to Jest in one of our projects, it worked like a charm. For reference, here are the minimal steps to switch to Jest in a new project:

  1. Create the project

    $ ng new myapp
    $ cd myapp
    
  2. Remove Karma dependencies, config file and test.ts:

    $ yarn remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
    $ rm src/karma.conf.js src/test.ts
    
  3. Install Jest builder, create the config file:

    $ yarn add --dev jest @angular-builders/jest
    $ touch src/jest.config.js
    
  4. Switch to commonjs in the src/tsconfig.spec.json:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/spec",
        "module": "commonjs",
        "types": [
          "jasmine",
          "node"
        ]
      },
      "include": [
        "**/*.spec.ts",
        "**/*.d.ts"
      ]
    }
    
  5. Switch to Jest builder in angular.json:

    {
      ...
        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
      ...
    }
    

Now you will be running the tests with Jest:

$ ng test
 PASS  src/app/app.component.spec.ts
  AppComponent
    ✓ should create the app (223ms)
    ✓ should have as title 'myapp' (80ms)
    ✓ should render title in a h1 tag (70ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.704s
Ran all test suites.

Upvotes: 1

Related Questions