liveBook · Manning

Ng test command

As explained in Modern Angular

ng test is an Angular CLI command that runs an Angular project's unit tests and their setup commands.

ng test runs an Angular project's unit tests and their setup commands. It initially uses the default Karma-based testing environment, but the Angular CLI test target can be redirected to Jest when the project requires it. section 8.2.2 section 8.3.1

A practical test-runner setup follows these steps:

  • Run ng test to execute the generated AppComponent specs and expose configuration or dependency failures. section 8.3
  • Use tsconfig.spec.json to include .spec.ts files and provide Jest compiler types. section 8.2.2
  • Change angular.json's test builder to the Jest builder, retain the testing polyfills, and point it to tsconfig.spec.json. section 8.2.2
  • Install Jest, its jsdom environment, and Jest types when the runner is missing; add setup-jest.ts through jest.config.ts for custom setup. section 8.2.2

Diagnosing a failing AppComponent test

Running ng test may reveal a NullInjectorError when AppComponent's AuthService requires HttpClient. After switching successfully to Jest, the reporting format changes, but dependency configuration still must be fixed before the component spec can initialize. section 8.2.2 section 8.3.1

Listing 8.2 angular.json configuration to use Jest as test runner
{
 #1
  "projects": {
    "hrms": {
      "projectType": "application",
      "architect": {
 #2
        "test": {
          "builder": "@angular-devkit/build-angular:jest",  #3
          "options": {
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json"
 #4
          }
        }
      }
    }
  }
}

Inspect the angular.json test target showing the Jest builder, testing polyfills, and tsconfig.spec.json linkage. section 8.2.2

How Modern Angular covers it

How deep it goes
Explains test discovery, runner replacement, dependency installation, and custom setup, stopping short of broader testing theory.
Examples
Uses generated AppComponent specs, Jest configuration files, and a NullInjectorError involving AuthService and HttpClient.
What it assumes
Assumes an Angular CLI project with generated specs and requires familiarity with project configuration files and dependency installation.
What you can do after
Operate Angular unit tests, switch the CLI test target to Jest, and interpret initialization failures.
How it connects
Connects Angular CLI testing with Karma, Jest, TestBed, tsconfig.spec.json, angular.json, and HttpClient dependency configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.