async-test.js 13 KB

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