async-test.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2022 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. (function (_global) {
  8. class AsyncTestZoneSpec {
  9. static { this.symbolParentUnresolved = Zone.__symbol__('parentUnresolved'); }
  10. constructor(finishCallback, failCallback, namePrefix) {
  11. this.finishCallback = finishCallback;
  12. this.failCallback = failCallback;
  13. this._pendingMicroTasks = false;
  14. this._pendingMacroTasks = false;
  15. this._alreadyErrored = false;
  16. this._isSync = false;
  17. this._existingFinishTimer = null;
  18. this.entryFunction = null;
  19. this.runZone = Zone.current;
  20. this.unresolvedChainedPromiseCount = 0;
  21. this.supportWaitUnresolvedChainedPromise = false;
  22. this.name = 'asyncTestZone for ' + namePrefix;
  23. this.properties = { 'AsyncTestZoneSpec': this };
  24. this.supportWaitUnresolvedChainedPromise =
  25. _global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
  26. }
  27. isUnresolvedChainedPromisePending() {
  28. return this.unresolvedChainedPromiseCount > 0;
  29. }
  30. _finishCallbackIfDone() {
  31. // NOTE: Technically the `onHasTask` could fire together with the initial synchronous
  32. // completion in `onInvoke`. `onHasTask` might call this method when it captured e.g.
  33. // microtasks in the proxy zone that now complete as part of this async zone run.
  34. // Consider the following scenario:
  35. // 1. A test `beforeEach` schedules a microtask in the ProxyZone.
  36. // 2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
  37. // 3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
  38. // 4. We wait the scheduled timeout (see below) to account for unhandled promises.
  39. // 5. The microtask from (1) finishes and `onHasTask` is invoked.
  40. // --> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
  41. // If the finish timeout from below is already scheduled, terminate the existing scheduled
  42. // finish invocation, avoiding calling `jasmine` `done` multiple times. *Note* that we would
  43. // want to schedule a new finish callback in case the task state changes again.
  44. if (this._existingFinishTimer !== null) {
  45. clearTimeout(this._existingFinishTimer);
  46. this._existingFinishTimer = null;
  47. }
  48. if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
  49. (this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
  50. // We wait until the next tick because we would like to catch unhandled promises which could
  51. // cause test logic to be executed. In such cases we cannot finish with tasks pending then.
  52. this.runZone.run(() => {
  53. this._existingFinishTimer = setTimeout(() => {
  54. if (!this._alreadyErrored && !(this._pendingMicroTasks || this._pendingMacroTasks)) {
  55. this.finishCallback();
  56. }
  57. }, 0);
  58. });
  59. }
  60. }
  61. patchPromiseForTest() {
  62. if (!this.supportWaitUnresolvedChainedPromise) {
  63. return;
  64. }
  65. const patchPromiseForTest = Promise[Zone.__symbol__('patchPromiseForTest')];
  66. if (patchPromiseForTest) {
  67. patchPromiseForTest();
  68. }
  69. }
  70. unPatchPromiseForTest() {
  71. if (!this.supportWaitUnresolvedChainedPromise) {
  72. return;
  73. }
  74. const unPatchPromiseForTest = Promise[Zone.__symbol__('unPatchPromiseForTest')];
  75. if (unPatchPromiseForTest) {
  76. unPatchPromiseForTest();
  77. }
  78. }
  79. onScheduleTask(delegate, current, target, task) {
  80. if (task.type !== 'eventTask') {
  81. this._isSync = false;
  82. }
  83. if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
  84. // check whether the promise is a chained promise
  85. if (task.data[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
  86. // chained promise is being scheduled
  87. this.unresolvedChainedPromiseCount--;
  88. }
  89. }
  90. return delegate.scheduleTask(target, task);
  91. }
  92. onInvokeTask(delegate, current, target, task, applyThis, applyArgs) {
  93. if (task.type !== 'eventTask') {
  94. this._isSync = false;
  95. }
  96. return delegate.invokeTask(target, task, applyThis, applyArgs);
  97. }
  98. onCancelTask(delegate, current, target, task) {
  99. if (task.type !== 'eventTask') {
  100. this._isSync = false;
  101. }
  102. return delegate.cancelTask(target, task);
  103. }
  104. // Note - we need to use onInvoke at the moment to call finish when a test is
  105. // fully synchronous. TODO(juliemr): remove this when the logic for
  106. // onHasTask changes and it calls whenever the task queues are dirty.
  107. // updated by(JiaLiPassion), only call finish callback when no task
  108. // was scheduled/invoked/canceled.
  109. onInvoke(parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {
  110. if (!this.entryFunction) {
  111. this.entryFunction = delegate;
  112. }
  113. try {
  114. this._isSync = true;
  115. return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
  116. }
  117. finally {
  118. // We need to check the delegate is the same as entryFunction or not.
  119. // Consider the following case.
  120. //
  121. // asyncTestZone.run(() => { // Here the delegate will be the entryFunction
  122. // Zone.current.run(() => { // Here the delegate will not be the entryFunction
  123. // });
  124. // });
  125. //
  126. // We only want to check whether there are async tasks scheduled
  127. // for the entry function.
  128. if (this._isSync && this.entryFunction === delegate) {
  129. this._finishCallbackIfDone();
  130. }
  131. }
  132. }
  133. onHandleError(parentZoneDelegate, currentZone, targetZone, error) {
  134. // Let the parent try to handle the error.
  135. const result = parentZoneDelegate.handleError(targetZone, error);
  136. if (result) {
  137. this.failCallback(error);
  138. this._alreadyErrored = true;
  139. }
  140. return false;
  141. }
  142. onHasTask(delegate, current, target, hasTaskState) {
  143. delegate.hasTask(target, hasTaskState);
  144. // We should only trigger finishCallback when the target zone is the AsyncTestZone
  145. // Consider the following cases.
  146. //
  147. // const childZone = asyncTestZone.fork({
  148. // name: 'child',
  149. // onHasTask: ...
  150. // });
  151. //
  152. // So we have nested zones declared the onHasTask hook, in this case,
  153. // the onHasTask will be triggered twice, and cause the finishCallbackIfDone()
  154. // is also be invoked twice. So we need to only trigger the finishCallbackIfDone()
  155. // when the current zone is the same as the target zone.
  156. if (current !== target) {
  157. return;
  158. }
  159. if (hasTaskState.change == 'microTask') {
  160. this._pendingMicroTasks = hasTaskState.microTask;
  161. this._finishCallbackIfDone();
  162. }
  163. else if (hasTaskState.change == 'macroTask') {
  164. this._pendingMacroTasks = hasTaskState.macroTask;
  165. this._finishCallbackIfDone();
  166. }
  167. }
  168. }
  169. // Export the class so that new instances can be created with proper
  170. // constructor params.
  171. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
  172. })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
  173. Zone.__load_patch('asynctest', (global, Zone, api) => {
  174. /**
  175. * Wraps a test function in an asynchronous test zone. The test will automatically
  176. * complete when all asynchronous calls within this zone are done.
  177. */
  178. Zone[api.symbol('asyncTest')] = function asyncTest(fn) {
  179. // If we're running using the Jasmine test framework, adapt to call the 'done'
  180. // function when asynchronous activity is finished.
  181. if (global.jasmine) {
  182. // Not using an arrow function to preserve context passed from call site
  183. return function (done) {
  184. if (!done) {
  185. // if we run beforeEach in @angular/core/testing/testing_internal then we get no done
  186. // fake it here and assume sync.
  187. done = function () { };
  188. done.fail = function (e) {
  189. throw e;
  190. };
  191. }
  192. runInTestZone(fn, this, done, (err) => {
  193. if (typeof err === 'string') {
  194. return done.fail(new Error(err));
  195. }
  196. else {
  197. done.fail(err);
  198. }
  199. });
  200. };
  201. }
  202. // Otherwise, return a promise which will resolve when asynchronous activity
  203. // is finished. This will be correctly consumed by the Mocha framework with
  204. // it('...', async(myFn)); or can be used in a custom framework.
  205. // Not using an arrow function to preserve context passed from call site
  206. return function () {
  207. return new Promise((finishCallback, failCallback) => {
  208. runInTestZone(fn, this, finishCallback, failCallback);
  209. });
  210. };
  211. };
  212. function runInTestZone(fn, context, finishCallback, failCallback) {
  213. const currentZone = Zone.current;
  214. const AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
  215. if (AsyncTestZoneSpec === undefined) {
  216. throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
  217. 'Please make sure that your environment includes zone.js/plugins/async-test');
  218. }
  219. const ProxyZoneSpec = Zone['ProxyZoneSpec'];
  220. if (!ProxyZoneSpec) {
  221. throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
  222. 'Please make sure that your environment includes zone.js/plugins/proxy');
  223. }
  224. const proxyZoneSpec = ProxyZoneSpec.get();
  225. ProxyZoneSpec.assertPresent();
  226. // We need to create the AsyncTestZoneSpec outside the ProxyZone.
  227. // If we do it in ProxyZone then we will get to infinite recursion.
  228. const proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
  229. const previousDelegate = proxyZoneSpec.getDelegate();
  230. proxyZone.parent.run(() => {
  231. const testZoneSpec = new AsyncTestZoneSpec(() => {
  232. // Need to restore the original zone.
  233. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  234. // Only reset the zone spec if it's
  235. // still this one. Otherwise, assume
  236. // it's OK.
  237. proxyZoneSpec.setDelegate(previousDelegate);
  238. }
  239. testZoneSpec.unPatchPromiseForTest();
  240. currentZone.run(() => {
  241. finishCallback();
  242. });
  243. }, (error) => {
  244. // Need to restore the original zone.
  245. if (proxyZoneSpec.getDelegate() == testZoneSpec) {
  246. // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
  247. proxyZoneSpec.setDelegate(previousDelegate);
  248. }
  249. testZoneSpec.unPatchPromiseForTest();
  250. currentZone.run(() => {
  251. failCallback(error);
  252. });
  253. }, 'test');
  254. proxyZoneSpec.setDelegate(testZoneSpec);
  255. testZoneSpec.patchPromiseForTest();
  256. });
  257. return Zone.current.runGuarded(fn, context);
  258. }
  259. });