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
