René's URL Explorer Experiment


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

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@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-profiling0
react-import-mapreact,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-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:e6712cfc-0fdf-cbce-4b7b-6c80c974da73
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-id9BC6:2C69FC:F62F4A:1482448:6B01DB98
html-safe-noncee88ee9998da4752a0e43962c73bd5d78e6854a35993ef7a41d7cc299604feb38
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5QkM2OjJDNjlGQzpGNjJGNEE6MTQ4MjQ0ODo2QjAxREI5OCIsInZpc2l0b3JfaWQiOiI1MTI0NTU5NTExMTI1ODc1NjA4IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmac179b7e68d0950edf11940f7b93da5d40177aa3017c8b1fcfc2a7887af77d8fc7
hovercard-subject-tagissue:6434798706
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/angular/angular/72070/issue_layout
twitter:imagehttps://opengraph.githubassets.com/079b7d60fbe8d9a14a8af6a71d46eb50dcd858490d79a5e442982a2dafd9f3cb/angular/angular/issues/72070
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/079b7d60fbe8d9a14a8af6a71d46eb50dcd858490d79a5e442982a2dafd9f3cb/angular/angular/issues/72070
og:image:altWhich @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:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamejayedge
hostnamegithub.com
expected-hostnamegithub.com
Nonecc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c
turbo-cache-controlno-preview
go-importgithub.com/angular/angular git https://github.com/angular/angular.git
octolytics-dimension-user_id139426
octolytics-dimension-user_loginangular
octolytics-dimension-repository_id24195339
octolytics-dimension-repository_nwoangular/angular
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id24195339
octolytics-dimension-repository_network_root_nwoangular/angular
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release8c77c9e8439031ad54c75a250694842892f693e1
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/angular/angular/issues/72070#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fangular%2Fangular%2Fissues%2F72070
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fangular%2Fangular%2Fissues%2F72070
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=angular%2Fangular
Reloadhttps://github.com/angular/angular/issues/72070
Reloadhttps://github.com/angular/angular/issues/72070
Reloadhttps://github.com/angular/angular/issues/72070
angularhttps://github.com/angular
angularhttps://github.com/angular/angular
Codehttps://github.com/angular/angular
Issues835 (835)https://github.com/angular/angular/issues
Pull requests142 (142)https://github.com/angular/angular/pulls
Discussionshttps://github.com/angular/angular/discussions
Actionshttps://github.com/angular/angular/actions
Projectshttps://github.com/angular/angular/projects
Security and quality40 (40)https://github.com/angular/angular/security
Insightshttps://github.com/angular/angular/insights
https://github.com/angular/angular
New issuehttps://github.com/login?return_to=https://github.com/angular/angular/issues/72070
New issuehttps://github.com/login?return_to=https://github.com/angular/angular/issues/72070
zone.js fakeAsync: cancelling a timer that was scheduled before fakeAsync() removes an unrelated fake timer with the same idhttps://github.com/angular/angular/issues/72070#top
area: zonesIssues related to zone.jshttps://github.com/angular/angular/issues?q=state%3Aopen%20label%3A%22area%3A%20zones%22
needsTriagehttps://github.com/angular/angular/milestone/83
https://github.com/jayedge
jayedgehttps://github.com/jayedge
on Nov 17, 2026https://github.com/angular/angular/issues/72070#issue-6434798706
#54600https://github.com/angular/angular/pull/54600
#54323https://github.com/angular/angular/issues/54323
https://github.com/jayedge/zonejs-fakeasync-cancel-reprohttps://github.com/jayedge/zonejs-fakeasync-cancel-repro
https://github.com/jayedge/zonejs-fakeasync-cancel-reprohttps://github.com/jayedge/zonejs-fakeasync-cancel-repro
angular-robothttps://github.com/apps/angular-robot
area: zonesIssues related to zone.jshttps://github.com/angular/angular/issues?q=state%3Aopen%20label%3A%22area%3A%20zones%22
on Nov 17, 2026https://github.com/angular/angular/issues/72070#event-36349849795
angular-robothttps://github.com/apps/angular-robot
needsTriagehttps://github.com/angular/angular/milestone/83
on Nov 17, 2026https://github.com/angular/angular/issues/72070#event-36349852524
Sign up for freehttps://github.com/signup?return_to=https://github.com/angular/angular/issues/72070
Sign in to commenthttps://github.com/login?return_to=https://github.com/angular/angular/issues/72070
area: zonesIssues related to zone.jshttps://github.com/angular/angular/issues?q=state%3Aopen%20label%3A%22area%3A%20zones%22
needsTriageNo due datehttps://github.com/angular/angular/milestone/83
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.