async-test.umd.js 14 KB

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