How to fix Angular Error: NG0908: In this configuration Angular requires Zone.js

Problem

When you’re using zoneless change detection with Angular v17+, when running the unit tests you will often encounter the following error (with the main app working properly):

Chrome 139.0.0.0 (Linux 0.0.0) App should create the app FAILED
        Error: NG0908: In this configuration Angular requires Zone.js
        error properties: Object({ code: 908 })
            at new _NgZone (node_modules/@angular/core/fesm2022/debug_node.mjs:16466:19)
            at Object.ngZoneFactory [as useFactory] (node_modules/@angular/core/fesm2022/debug_node.mjs:30575:29)
            at Object.factory (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:2257:38)
            at node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:2154:47
            at runInInjectorProfilerContext (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:720:9)
            at R3Injector.hydrate (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:2152:21)
            at R3Injector.get (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:2007:33)
            at R3Injector.retrieve (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:1903:25)
            at injectInjectorOnly (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:1020:39)
            at ɵɵinject (node_modules/@angular/core/fesm2022/root_effect_scheduler.mjs:1032:42)

Solution

You need to configure each test file (*.spec.ts) individually to use zoneless change detection by adding provideZonelessChangeDetection() to the providers array in the TestBed configuration.

describe('App', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [App],
      // Add provideZonelessChangeDetection() here!
      providers: [provideZonelessChangeDetection()]
    }).compileComponents();
  });
  // ...

Copilot prompt

A suitable propmpt for GitHub copilot or other tools is:

Add provideZonelessChangeDetection() to the providers array of "await TestBed.configureTestingModule" in *.spec.ts in #codebase