Repository navigation
Description
Which @angular/* package(s) are the source of the bug?
zone.js
Is this a regression?
No
Description
Inside fakeAsync(), cancelling a timer task that was scheduled before the test entered fakeAsync() is routed (via the ProxyZoneSpec) to FakeAsyncTestZoneSpec.onCancelTask. That method assumes it owns the task and does
case 'setTimeout':
case 'requestAnimationFrame':
return this._clearTimeout(task.data['handleId']);
case 'setInterval':
return this._clearInterval(task.data['handleId']);i.e. it removes whichever fake timer has the same numeric id as the real timer being cancelled. It never checks that it scheduled the task.
Fake ids are taken from the native setTimeout id pool (#54600, the fix for #54323), so they don't collide with real setTimeout ids. requestAnimationFrame ids come from a separate native counter, so they can. Scheduler.nextId is seeded once, at load time, from a native setTimeout id. In a new CLI project's Karma page that is 1, and the page's first rAF is also 1.
Angular hits this path by itself when TestBed is zoneless. TestBed.createComponent() in a beforeEach (outside fakeAsync) makes the change-detection scheduler arm its setTimeout + requestAnimationFrame race (scheduleCallbackWithRafRace) in the ProxyZone. The end of the test's first fixture.detectChanges() inside fakeAsync() then cancels that pending callback, after ngOnInit has run. If a fake timer was queued during that detectChanges() (e.g. an RxJS debounceTime set up in ngOnInit, whose AsyncAction uses setInterval) and got the colliding id, cancelAnimationFrame(1) silently deletes it from the fake queue, and tick() never runs it. Logged in the reproduction below: real setTimeout 4 and rAF 1 armed by createComponent(), Scheduler.nextId 1 on entering fakeAsync(), cancelAnimationFrame(1) during detectChanges(), then 0 queued fake timers while pendingPeriodicTimers still lists the interval.
TestBed is zoneless by default, but the CLI's generated test entry point (@angular/build, for Karma and for Vitest) adds provideZoneChangeDetection() whenever zone.js is loaded. With zone change detection, createComponent() arms no rAF in this case and nothing collides. So the Angular case needs a zoneless TestBed: a zoneless app whose tests still use fakeAsync() (provideZonelessChangeDetection() in the test), or a test entry point that calls initTestEnvironment() without zone providers.
The visible symptom is an order-dependent test. It fails every time when it is the first test the browser runs (e.g. focused, or run with --include), and passes once an earlier test has armed a rAF or a fake timer. With Jasmine's random order a full run fails intermittently: alongside one other spec it failed in 1 of 4 runs.
The same code path also means the real timer is never cleared natively: onCancelTask doesn't call delegate.cancelTask() for these sources, so a real setTimeout cancelled inside fakeAsync() still fires later. In Angular's case that's harmless because the scheduler also swaps its callback for a no-op.
Reproduction
Repository: https://github.com/jayedge/zonejs-fakeasync-cancel-repro
A new CLI project (ng new --test-runner=karma --zoneless=false) plus two specs. Run each on its own, so it is the first test the browser runs:
npx ng test --watch=false --include src/app/debounce-cancel.spec.ts
npx ng test --watch=false --include src/app/raf-cancel.spec.ts
src/app/debounce-cancel.spec.ts:
import { Component, OnInit, provideZonelessChangeDetection } from '@angular/core';
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { BehaviorSubject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Component({ selector: 'app-search', template: '{{ result }}' })
class SearchComponent implements OnInit {
readonly query = new BehaviorSubject<string>('');
result = '';
ngOnInit(): void {
// BehaviorSubject replays '' on subscribe, so the debounce arms its setInterval during ngOnInit.
this.query.pipe(debounceTime(150)).subscribe((value) => (this.result = value));
}
}
describe('fakeAsync with zoneless Angular change detection', () => {
let fixture: ComponentFixture<SearchComponent>;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [SearchComponent], providers: [provideZonelessChangeDetection()] });
fixture = TestBed.createComponent(SearchComponent); // outside fakeAsync()
});
it('fires a debounce armed during the first detectChanges()', fakeAsync(() => {
fixture.detectChanges();
fixture.componentInstance.query.next('x');
tick(150);
expect(fixture.componentInstance.result).toBe('x'); // fails when this is the first test: ''
}));
});src/app/raf-cancel.spec.ts (zone.js only, no TestBed):
import { fakeAsync, tick } from '@angular/core/testing';
declare const Zone: any; // zone.js global; a new CLI project has no typings for it
describe('fakeAsync, zone.js only', () => {
let rafId: number;
beforeEach(() => {
rafId = requestAnimationFrame(() => {}); // outside fakeAsync()
});
it('keeps a fake timer whose id equals the cancelled rAF id', fakeAsync(() => {
// Force the id coincidence (private static). In the Angular case the first fake id and the first rAF id are both 1.
(Zone.current.get('FakeAsyncTestZoneSpec') as any)._scheduler.constructor.nextId = rafId;
let runs = 0;
const intervalId = window.setInterval(() => runs++, 150);
expect(intervalId).toBe(rafId); // passes: the collision is in place
cancelAnimationFrame(rafId); // cancels the REAL rAF...
tick(150);
expect(runs).toBe(1); // ...but the fake interval is gone: 0
clearInterval(intervalId);
}));
});Run on its own, the first failed 3 of 3 times. The second forces the collision, so it fails in every run, alone or not. With the workaround below loaded, both pass.
First seen in an application's suite on Angular 21.2 with zone.js 0.16.2, whose own test entry point leaves TestBed zoneless.
Please provide a link to a minimal reproduction of the bug
https://github.com/jayedge/zonejs-fakeasync-cancel-repro
Please provide the exception or error you saw
fakeAsync with zoneless Angular change detection fires a debounce armed during the first detectChanges() FAILED
Expected '' to be 'x'.
fakeAsync, zone.js only keeps a fake timer whose id equals the cancelled rAF id FAILED
Expected 0 to be 1.
Please provide the environment you discovered this bug in (run ng version)
Angular CLI : 22.2.7
Angular : 22.2.6
Node.js : 24.18.0
Package Manager : npm 12.0.2
Operating System : darwin arm64
+---------------------------+-------------------+-------------------+
| Package | Installed Version | Requested Version |
+---------------------------+-------------------+-------------------+
| @angular/build | 22.2.7 | ^22.2.6 |
| @angular/cli | 22.2.7 | ^22.2.6 |
| @angular/common | 22.2.6 | ^22.2.0 |
| @angular/compiler | 22.2.6 | ^22.2.0 |
| @angular/compiler-cli | 22.2.6 | ^22.2.0 |
| @angular/core | 22.2.6 | ^22.2.0 |
| @angular/forms | 22.2.6 | ^22.2.0 |
| @angular/platform-browser | 22.2.6 | ^22.2.0 |
| @angular/router | 22.2.6 | ^22.2.0 |
| rxjs | 7.8.2 | ~7.8.0 |
| typescript | 6.0.3 | ~6.0.2 |
| zone.js | 0.16.3 | ~0.16.0 |
+---------------------------+-------------------+-------------------+
karma 6.4.4, karma-jasmine 5.1.0, jasmine-core 6.3.0, Chrome Headless 149
Anything else?
Suggested fix: make FakeAsyncTestZoneSpec cancel a task only in the instance that scheduled it, and hand a task no instance scheduled to the parent delegate. That is the same thing ProxyZoneSpec does when it has no delegate. The owner has to be recorded across instances, not per instance: with two fakeAsync() blocks in one spec (e.g. beforeEach(fakeAsync(...)) and it(fakeAsync(...))), a fake timer left by the first and cancelled during the second would otherwise go native with a fake id. Sketch:
const scheduledBy = new WeakMap<Task, FakeAsyncTestZoneSpec>(); // module-level, shared by all instances
onScheduleTask(delegate, current, target, task) {
// ...existing switch; wherever task.data['handleId'] is assigned from _setTimeout/_setInterval:
scheduledBy.set(task, this);
return task;
}
onCancelTask(delegate, current, target, task) {
const owner = scheduledBy.get(task);
if (owner === undefined) {
return delegate.cancelTask(target, task); // no fake zone scheduled it: let the real timer be cleared natively
}
// ...existing switch, run against owner instead of this
}Changing how fake ids are allocated alone would not be enough. The cancel path would still treat a foreign task's native id as a fake one.
Workaround: patch the same two hooks from outside, after zone.js/testing has loaded and before any spec runs. The @angular/build:unit-test Karma runner ignores setupFiles, so import it from a spec module (or from your own test entry point):
declare const Zone: any;
const fakeAsyncHooks = Zone['FakeAsyncTestZoneSpec'].prototype;
const scheduledBy = new WeakMap<object, object>();
const originalScheduleTask = fakeAsyncHooks.onScheduleTask;
const originalCancelTask = fakeAsyncHooks.onCancelTask;
fakeAsyncHooks.onScheduleTask = function (this: object, delegate: any, current: any, target: any, task: any) {
const scheduled = originalScheduleTask.call(this, delegate, current, target, task);
scheduledBy.set(scheduled, this);
return scheduled;
};
fakeAsyncHooks.onCancelTask = function (delegate: any, current: any, target: any, task: any) {
const owner = scheduledBy.get(task);
return owner === undefined
? delegate.cancelTask(target, task)
: originalCancelTask.call(owner, delegate, current, target, task);
};With this in place both specs above pass when run on their own.
Activity