task-tracking.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. /**
  9. * A `TaskTrackingZoneSpec` allows one to track all outstanding Tasks.
  10. *
  11. * This is useful in tests. For example to see which tasks are preventing a test from completing
  12. * or an automated way of releasing all of the event listeners at the end of the test.
  13. */
  14. class TaskTrackingZoneSpec implements ZoneSpec {
  15. name = 'TaskTrackingZone';
  16. microTasks: Task[] = [];
  17. macroTasks: Task[] = [];
  18. eventTasks: Task[] = [];
  19. properties: {[key: string]: any} = {'TaskTrackingZone': this};
  20. static get() {
  21. return Zone.current.get('TaskTrackingZone');
  22. }
  23. private getTasksFor(type: string): Task[] {
  24. switch (type) {
  25. case 'microTask':
  26. return this.microTasks;
  27. case 'macroTask':
  28. return this.macroTasks;
  29. case 'eventTask':
  30. return this.eventTasks;
  31. }
  32. throw new Error('Unknown task format: ' + type);
  33. }
  34. onScheduleTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
  35. Task {
  36. (task as any)['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: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
  42. any {
  43. const tasks = this.getTasksFor(task.type);
  44. for (let i = 0; i < tasks.length; i++) {
  45. if (tasks[i] == task) {
  46. tasks.splice(i, 1);
  47. break;
  48. }
  49. }
  50. return parentZoneDelegate.cancelTask(targetZone, task);
  51. }
  52. onInvokeTask(
  53. parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
  54. applyThis: any, applyArgs: any): any {
  55. if (task.type === 'eventTask')
  56. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  57. const tasks = this.getTasksFor(task.type);
  58. for (let i = 0; i < tasks.length; i++) {
  59. if (tasks[i] == task) {
  60. tasks.splice(i, 1);
  61. break;
  62. }
  63. }
  64. return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
  65. }
  66. clearEvents() {
  67. while (this.eventTasks.length) {
  68. Zone.current.cancelTask(this.eventTasks[0]);
  69. }
  70. }
  71. }
  72. // Export the class so that new instances can be created with proper
  73. // constructor params.
  74. (Zone as any)['TaskTrackingZoneSpec'] = TaskTrackingZoneSpec;