async-test.umd.js 14 KB

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