task-tracking.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2022 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. constructor() {
  15. this.name = 'TaskTrackingZone';
  16. this.microTasks = [];
  17. this.macroTasks = [];
  18. this.eventTasks = [];
  19. this.properties = { 'TaskTrackingZone': this };
  20. }
  21. static get() {
  22. return Zone.current.get('TaskTrackingZone');
  23. }
  24. getTasksFor(type) {
  25. switch (type) {
  26. case 'microTask':
  27. return this.microTasks;
  28. case 'macroTask':
  29. return this.macroTasks;
  30. case 'eventTask':
  31. return this.eventTasks;
  32. }
  33. throw new Error('Unknown task format: ' + type);
  34. }
  35. onScheduleTask(parentZoneDelegate, currentZone, targetZone, task) {
  36. task['creationLocation'] = new Error(`Task '${task.type}' from '${task.source}'.`);
  37. const tasks = this.getTasksFor(task.type);
  38. tasks.push(task);
  39. return parentZoneDelegate.scheduleTask(targetZone, task);
  40. }
  41. onCancelTask(parentZoneDelegate, currentZone, targetZone, task) {
  42. const tasks = this.getTasksFor(task.type);
  43. for (let i = 0; i < tasks.length; i++) {
  44. if (tasks[i] == task) {
  45. tasks.splice(i, 1);
  46. break;
  47. }
  48. }
  49. return parentZoneDelegate.cancelTask(targetZone, task);
  50. }
  51. onInvokeTask(parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs) {
  52. if (task.type === 'eventTask' || task.data?.isPeriodic)
  53. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  54. const tasks = this.getTasksFor(task.type);
  55. for (let i = 0; i < tasks.length; i++) {
  56. if (tasks[i] == task) {
  57. tasks.splice(i, 1);
  58. break;
  59. }
  60. }
  61. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  62. }
  63. clearEvents() {
  64. while (this.eventTasks.length) {
  65. Zone.current.cancelTask(this.eventTasks[0]);
  66. }
  67. }
  68. }
  69. // Export the class so that new instances can be created with proper
  70. // constructor params.
  71. Zone['TaskTrackingZoneSpec'] = TaskTrackingZoneSpec;