Title: zone.js `fakeAsync`: cancelling a timer that was scheduled before `fakeAsync()` removes an unrelated fake timer with the same id · Issue #72070 · angular/angular · GitHub
Open Graph Title: zone.js `fakeAsync`: cancelling a timer that was scheduled before `fakeAsync()` removes an unrelated fake timer with the same id · Issue #72070 · angular/angular
X Title: zone.js `fakeAsync`: cancelling a timer that was scheduled before `fakeAsync()` removes an unrelated fake timer with the same id · Issue #72070 · angular/angular
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 F...
Open Graph 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(...
X 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(...
Opengraph URL: https://github.com/angular/angular/issues/72070
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"zone.js `fakeAsync`: cancelling a timer that was scheduled before `fakeAsync()` removes an unrelated fake timer with the same id","articleBody":"### Which @angular/* package(s) are the source of the bug?\n\nzone.js\n\n### Is this a regression?\n\nNo\n\n### Description\n\nInside `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\n\n```js\ncase 'setTimeout':\ncase 'requestAnimationFrame':\n return this._clearTimeout(task.data['handleId']);\ncase 'setInterval':\n return this._clearInterval(task.data['handleId']);\n```\n\ni.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.\n\nFake 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`.\n\nAngular 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.\n\nTestBed 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.\n\nThe 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.\n\nThe 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.\n\n### Reproduction\n\nRepository: https://github.com/jayedge/zonejs-fakeasync-cancel-repro\n\nA 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:\n\n```\nnpx ng test --watch=false --include src/app/debounce-cancel.spec.ts\nnpx ng test --watch=false --include src/app/raf-cancel.spec.ts\n```\n\n`src/app/debounce-cancel.spec.ts`:\n\n```ts\nimport { Component, OnInit, provideZonelessChangeDetection } from '@angular/core';\nimport { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';\nimport { BehaviorSubject } from 'rxjs';\nimport { debounceTime } from 'rxjs/operators';\n\n@Component({ selector: 'app-search', template: '{{ result }}' })\nclass SearchComponent implements OnInit {\n readonly query = new BehaviorSubject\u003cstring>('');\n result = '';\n\n ngOnInit(): void {\n // BehaviorSubject replays '' on subscribe, so the debounce arms its setInterval during ngOnInit.\n this.query.pipe(debounceTime(150)).subscribe((value) => (this.result = value));\n }\n}\n\ndescribe('fakeAsync with zoneless Angular change detection', () => {\n let fixture: ComponentFixture\u003cSearchComponent>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({ imports: [SearchComponent], providers: [provideZonelessChangeDetection()] });\n fixture = TestBed.createComponent(SearchComponent); // outside fakeAsync()\n });\n\n it('fires a debounce armed during the first detectChanges()', fakeAsync(() => {\n fixture.detectChanges();\n fixture.componentInstance.query.next('x');\n tick(150);\n expect(fixture.componentInstance.result).toBe('x'); // fails when this is the first test: ''\n }));\n});\n```\n\n`src/app/raf-cancel.spec.ts` (zone.js only, no TestBed):\n\n```ts\nimport { fakeAsync, tick } from '@angular/core/testing';\n\ndeclare const Zone: any; // zone.js global; a new CLI project has no typings for it\n\ndescribe('fakeAsync, zone.js only', () => {\n let rafId: number;\n\n beforeEach(() => {\n rafId = requestAnimationFrame(() => {}); // outside fakeAsync()\n });\n\n it('keeps a fake timer whose id equals the cancelled rAF id', fakeAsync(() => {\n // Force the id coincidence (private static). In the Angular case the first fake id and the first rAF id are both 1.\n (Zone.current.get('FakeAsyncTestZoneSpec') as any)._scheduler.constructor.nextId = rafId;\n let runs = 0;\n const intervalId = window.setInterval(() => runs++, 150);\n expect(intervalId).toBe(rafId); // passes: the collision is in place\n\n cancelAnimationFrame(rafId); // cancels the REAL rAF...\n tick(150);\n\n expect(runs).toBe(1); // ...but the fake interval is gone: 0\n clearInterval(intervalId);\n }));\n});\n```\n\nRun 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.\n\nFirst seen in an application's suite on Angular 21.2 with zone.js 0.16.2, whose own test entry point leaves TestBed zoneless.\n\n\n### Please provide a link to a minimal reproduction of the bug\n\nhttps://github.com/jayedge/zonejs-fakeasync-cancel-repro\n\n### Please provide the exception or error you saw\n\n```true\nfakeAsync with zoneless Angular change detection fires a debounce armed during the first detectChanges() FAILED\n Expected '' to be 'x'.\n\nfakeAsync, zone.js only keeps a fake timer whose id equals the cancelled rAF id FAILED\n Expected 0 to be 1.\n```\n\n### Please provide the environment you discovered this bug in (run `ng version`)\n\n```true\nAngular CLI : 22.2.7\nAngular : 22.2.6\nNode.js : 24.18.0\nPackage Manager : npm 12.0.2\nOperating System : darwin arm64\n\n+---------------------------+-------------------+-------------------+\n| Package | Installed Version | Requested Version |\n+---------------------------+-------------------+-------------------+\n| @angular/build | 22.2.7 | ^22.2.6 |\n| @angular/cli | 22.2.7 | ^22.2.6 |\n| @angular/common | 22.2.6 | ^22.2.0 |\n| @angular/compiler | 22.2.6 | ^22.2.0 |\n| @angular/compiler-cli | 22.2.6 | ^22.2.0 |\n| @angular/core | 22.2.6 | ^22.2.0 |\n| @angular/forms | 22.2.6 | ^22.2.0 |\n| @angular/platform-browser | 22.2.6 | ^22.2.0 |\n| @angular/router | 22.2.6 | ^22.2.0 |\n| rxjs | 7.8.2 | ~7.8.0 |\n| typescript | 6.0.3 | ~6.0.2 |\n| zone.js | 0.16.3 | ~0.16.0 |\n+---------------------------+-------------------+-------------------+\n\nkarma 6.4.4, karma-jasmine 5.1.0, jasmine-core 6.3.0, Chrome Headless 149\n```\n\n### Anything else?\n\n**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:\n\n```ts\nconst scheduledBy = new WeakMap\u003cTask, FakeAsyncTestZoneSpec>(); // module-level, shared by all instances\n\nonScheduleTask(delegate, current, target, task) {\n // ...existing switch; wherever task.data['handleId'] is assigned from _setTimeout/_setInterval:\n scheduledBy.set(task, this);\n return task;\n}\n\nonCancelTask(delegate, current, target, task) {\n const owner = scheduledBy.get(task);\n if (owner === undefined) {\n return delegate.cancelTask(target, task); // no fake zone scheduled it: let the real timer be cleared natively\n }\n // ...existing switch, run against owner instead of this\n}\n```\n\nChanging 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.\n\n**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):\n\n```ts\ndeclare const Zone: any;\n\nconst fakeAsyncHooks = Zone['FakeAsyncTestZoneSpec'].prototype;\nconst scheduledBy = new WeakMap\u003cobject, object>();\nconst originalScheduleTask = fakeAsyncHooks.onScheduleTask;\nconst originalCancelTask = fakeAsyncHooks.onCancelTask;\n\nfakeAsyncHooks.onScheduleTask = function (this: object, delegate: any, current: any, target: any, task: any) {\n const scheduled = originalScheduleTask.call(this, delegate, current, target, task);\n scheduledBy.set(scheduled, this);\n return scheduled;\n};\n\nfakeAsyncHooks.onCancelTask = function (delegate: any, current: any, target: any, task: any) {\n const owner = scheduledBy.get(task);\n return owner === undefined\n ? delegate.cancelTask(target, task)\n : originalCancelTask.call(owner, delegate, current, target, task);\n};\n```\n\nWith this in place both specs above pass when run on their own.\n","author":{"url":"https://github.com/jayedge","@type":"Person","name":"jayedge"},"datePublished":"2026-11-17T01:25:50Z","url":"https://github.com/angular/angular/issues/72070"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:e6712cfc-0fdf-cbce-4b7b-6c80c974da73 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9BC6:2C69FC:F62F4A:1482448:6B01DB98 |
| html-safe-nonce | e88ee9998da4752a0e43962c73bd5d78e6854a35993ef7a41d7cc299604feb38 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QkM2OjJDNjlGQzpGNjJGNEE6MTQ4MjQ0ODo2QjAxREI5OCIsInZpc2l0b3JfaWQiOiI1MTI0NTU5NTExMTI1ODc1NjA4IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 179b7e68d0950edf11940f7b93da5d40177aa3017c8b1fcfc2a7887af77d8fc7 |
| hovercard-subject-tag | issue:6434798706 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/angular/angular/72070/issue_layout |
| twitter:image | https://opengraph.githubassets.com/079b7d60fbe8d9a14a8af6a71d46eb50dcd858490d79a5e442982a2dafd9f3cb/angular/angular/issues/72070 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/079b7d60fbe8d9a14a8af6a71d46eb50dcd858490d79a5e442982a2dafd9f3cb/angular/angular/issues/72070 |
| og:image:alt | 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(... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | jayedge |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/angular/angular git https://github.com/angular/angular.git |
| octolytics-dimension-user_id | 139426 |
| octolytics-dimension-user_login | angular |
| octolytics-dimension-repository_id | 24195339 |
| octolytics-dimension-repository_nwo | angular/angular |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 24195339 |
| octolytics-dimension-repository_network_root_nwo | angular/angular |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width