task-tracking.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2025 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. /**
  8. * A `TaskTrackingZoneSpec` allows one to track all outstanding Tasks.
  9. *
  10. * This is useful in tests. For example to see which tasks are preventing a test from completing
  11. * or an automated way of releasing all of the event listeners at the end of the test.
  12. */
  13. class TaskTrackingZoneSpec {
  14. name = 'TaskTrackingZone';
  15. microTasks = [];
  16. macroTasks = [];
  17. eventTasks = [];
  18. properties = { 'TaskTrackingZone': this };
  19. static get() {
  20. return Zone.current.get('TaskTrackingZone');
  21. }
  22. getTasksFor(type) {
  23. switch (type) {
  24. case 'microTask':
  25. return this.microTasks;
  26. case 'macroTask':
  27. return this.macroTasks;
  28. case 'eventTask':
  29. return this.eventTasks;
  30. }
  31. throw new Error('Unknown task format: ' + type);
  32. }
  33. onScheduleTask(parentZoneDelegate, currentZone, targetZone, task) {
  34. task['creationLocation'] = new Error(`Task '${task.type}' from '${task.source}'.`);
  35. const tasks = this.getTasksFor(task.type);
  36. tasks.push(task);
  37. return parentZoneDelegate.scheduleTask(targetZone, task);
  38. }
  39. onCancelTask(parentZoneDelegate, currentZone, targetZone, task) {
  40. const tasks = this.getTasksFor(task.type);
  41. for (let i = 0; i < tasks.length; i++) {
  42. if (tasks[i] == task) {
  43. tasks.splice(i, 1);
  44. break;
  45. }
  46. }
  47. return parentZoneDelegate.cancelTask(targetZone, task);
  48. }
  49. onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  50. if (task.type === 'eventTask' || task.data?.isPeriodic)
  51. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  52. const tasks = this.getTasksFor(task.type);
  53. for (let i = 0; i < tasks.length; i++) {
  54. if (tasks[i] == task) {
  55. tasks.splice(i, 1);
  56. break;
  57. }
  58. }
  59. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  60. }
  61. clearEvents() {
  62. while (this.eventTasks.length) {
  63. Zone.current.cancelTask(this.eventTasks[0]);
  64. }
  65. }
  66. }
  67. function patchTaskTracking(Zone) {
  68. // Export the class so that new instances can be created with proper
  69. // constructor params.
  70. Zone['TaskTrackingZoneSpec'] = TaskTrackingZoneSpec;
  71. }
  72. patchTaskTracking(Zone);