jasmine-patch.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. 'use strict';
  2. /**
  3. * @license Angular v<unknown>
  4. * (c) 2010-2025 Google LLC. https://angular.io/
  5. * License: MIT
  6. */
  7. function patchJasmine(Zone) {
  8. Zone.__load_patch('jasmine', (global, Zone, api) => {
  9. const __extends = function (d, b) {
  10. for (const p in b)
  11. if (b.hasOwnProperty(p))
  12. d[p] = b[p];
  13. function __() {
  14. this.constructor = d;
  15. }
  16. d.prototype =
  17. b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
  18. };
  19. // Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
  20. // in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
  21. if (!Zone)
  22. throw new Error('Missing: zone.js');
  23. if (typeof jest !== 'undefined') {
  24. // return if jasmine is a light implementation inside jest
  25. // in this case, we are running inside jest not jasmine
  26. return;
  27. }
  28. if (typeof jasmine == 'undefined' || jasmine['__zone_patch__']) {
  29. return;
  30. }
  31. jasmine['__zone_patch__'] = true;
  32. const SyncTestZoneSpec = Zone['SyncTestZoneSpec'];
  33. const ProxyZoneSpec = Zone['ProxyZoneSpec'];
  34. if (!SyncTestZoneSpec)
  35. throw new Error('Missing: SyncTestZoneSpec');
  36. if (!ProxyZoneSpec)
  37. throw new Error('Missing: ProxyZoneSpec');
  38. const ambientZone = Zone.current;
  39. const symbol = Zone.__symbol__;
  40. // whether patch jasmine clock when in fakeAsync
  41. const disablePatchingJasmineClock = global[symbol('fakeAsyncDisablePatchingClock')] === true;
  42. // the original variable name fakeAsyncPatchLock is not accurate, so the name will be
  43. // fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we
  44. // also automatically disable the auto jump into fakeAsync feature
  45. const enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
  46. (global[symbol('fakeAsyncPatchLock')] === true ||
  47. global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true);
  48. const ignoreUnhandledRejection = global[symbol('ignoreUnhandledRejection')] === true;
  49. if (!ignoreUnhandledRejection) {
  50. const globalErrors = jasmine.GlobalErrors;
  51. if (globalErrors && !jasmine[symbol('GlobalErrors')]) {
  52. jasmine[symbol('GlobalErrors')] = globalErrors;
  53. jasmine.GlobalErrors = function () {
  54. const instance = new globalErrors();
  55. const originalInstall = instance.install;
  56. if (originalInstall && !instance[symbol('install')]) {
  57. instance[symbol('install')] = originalInstall;
  58. instance.install = function () {
  59. const isNode = typeof process !== 'undefined' && !!process.on;
  60. // Note: Jasmine checks internally if `process` and `process.on` is defined.
  61. // Otherwise, it installs the browser rejection handler through the
  62. // `global.addEventListener`. This code may be run in the browser environment where
  63. // `process` is not defined, and this will lead to a runtime exception since webpack 5
  64. // removed automatic Node.js polyfills. Note, that events are named differently, it's
  65. // `unhandledRejection` in Node.js and `unhandledrejection` in the browser.
  66. const originalHandlers = isNode
  67. ? process.listeners('unhandledRejection')
  68. : global.eventListeners('unhandledrejection');
  69. const result = originalInstall.apply(this, arguments);
  70. isNode
  71. ? process.removeAllListeners('unhandledRejection')
  72. : global.removeAllListeners('unhandledrejection');
  73. if (originalHandlers) {
  74. originalHandlers.forEach((handler) => {
  75. if (isNode) {
  76. process.on('unhandledRejection', handler);
  77. }
  78. else {
  79. global.addEventListener('unhandledrejection', handler);
  80. }
  81. });
  82. }
  83. return result;
  84. };
  85. }
  86. return instance;
  87. };
  88. }
  89. }
  90. // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
  91. const jasmineEnv = jasmine.getEnv();
  92. ['describe', 'xdescribe', 'fdescribe'].forEach((methodName) => {
  93. let originalJasmineFn = jasmineEnv[methodName];
  94. jasmineEnv[methodName] = function (description, specDefinitions) {
  95. return originalJasmineFn.call(this, description, wrapDescribeInZone(description, specDefinitions));
  96. };
  97. });
  98. ['it', 'xit', 'fit'].forEach((methodName) => {
  99. let originalJasmineFn = jasmineEnv[methodName];
  100. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  101. jasmineEnv[methodName] = function (description, specDefinitions, timeout) {
  102. arguments[1] = wrapTestInZone(specDefinitions);
  103. return originalJasmineFn.apply(this, arguments);
  104. };
  105. });
  106. ['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach((methodName) => {
  107. let originalJasmineFn = jasmineEnv[methodName];
  108. jasmineEnv[symbol(methodName)] = originalJasmineFn;
  109. jasmineEnv[methodName] = function (specDefinitions, timeout) {
  110. arguments[0] = wrapTestInZone(specDefinitions);
  111. return originalJasmineFn.apply(this, arguments);
  112. };
  113. });
  114. if (!disablePatchingJasmineClock) {
  115. // need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
  116. // they can work properly in FakeAsyncTest
  117. const originalClockFn = (jasmine[symbol('clock')] = jasmine['clock']);
  118. jasmine['clock'] = function () {
  119. const clock = originalClockFn.apply(this, arguments);
  120. if (!clock[symbol('patched')]) {
  121. clock[symbol('patched')] = symbol('patched');
  122. const originalTick = (clock[symbol('tick')] = clock.tick);
  123. clock.tick = function () {
  124. const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  125. if (fakeAsyncZoneSpec) {
  126. return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
  127. }
  128. return originalTick.apply(this, arguments);
  129. };
  130. const originalMockDate = (clock[symbol('mockDate')] = clock.mockDate);
  131. clock.mockDate = function () {
  132. const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
  133. if (fakeAsyncZoneSpec) {
  134. const dateTime = arguments.length > 0 ? arguments[0] : new Date();
  135. return fakeAsyncZoneSpec.setFakeBaseSystemTime.apply(fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function'
  136. ? [dateTime.getTime()]
  137. : arguments);
  138. }
  139. return originalMockDate.apply(this, arguments);
  140. };
  141. // for auto go into fakeAsync feature, we need the flag to enable it
  142. if (enableAutoFakeAsyncWhenClockPatched) {
  143. ['install', 'uninstall'].forEach((methodName) => {
  144. const originalClockFn = (clock[symbol(methodName)] = clock[methodName]);
  145. clock[methodName] = function () {
  146. const FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
  147. if (FakeAsyncTestZoneSpec) {
  148. jasmine[symbol('clockInstalled')] = 'install' === methodName;
  149. return;
  150. }
  151. return originalClockFn.apply(this, arguments);
  152. };
  153. });
  154. }
  155. }
  156. return clock;
  157. };
  158. }
  159. // monkey patch createSpyObj to make properties enumerable to true
  160. if (!jasmine[Zone.__symbol__('createSpyObj')]) {
  161. const originalCreateSpyObj = jasmine.createSpyObj;
  162. jasmine[Zone.__symbol__('createSpyObj')] = originalCreateSpyObj;
  163. jasmine.createSpyObj = function () {
  164. const args = Array.prototype.slice.call(arguments);
  165. const propertyNames = args.length >= 3 ? args[2] : null;
  166. let spyObj;
  167. if (propertyNames) {
  168. const defineProperty = Object.defineProperty;
  169. Object.defineProperty = function (obj, p, attributes) {
  170. return defineProperty.call(this, obj, p, {
  171. ...attributes,
  172. configurable: true,
  173. enumerable: true,
  174. });
  175. };
  176. try {
  177. spyObj = originalCreateSpyObj.apply(this, args);
  178. }
  179. finally {
  180. Object.defineProperty = defineProperty;
  181. }
  182. }
  183. else {
  184. spyObj = originalCreateSpyObj.apply(this, args);
  185. }
  186. return spyObj;
  187. };
  188. }
  189. /**
  190. * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
  191. * synchronous-only zone.
  192. */
  193. function wrapDescribeInZone(description, describeBody) {
  194. return function () {
  195. // Create a synchronous-only zone in which to run `describe` blocks in order to raise an
  196. // error if any asynchronous operations are attempted inside of a `describe`.
  197. const syncZone = ambientZone.fork(new SyncTestZoneSpec(`jasmine.describe#${description}`));
  198. return syncZone.run(describeBody, this, arguments);
  199. };
  200. }
  201. function runInTestZone(testBody, applyThis, queueRunner, done) {
  202. const isClockInstalled = !!jasmine[symbol('clockInstalled')];
  203. queueRunner.testProxyZoneSpec;
  204. const testProxyZone = queueRunner.testProxyZone;
  205. if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
  206. // auto run a fakeAsync
  207. const fakeAsyncModule = Zone[Zone.__symbol__('fakeAsyncTest')];
  208. if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
  209. testBody = fakeAsyncModule.fakeAsync(testBody);
  210. }
  211. }
  212. if (done) {
  213. return testProxyZone.run(testBody, applyThis, [done]);
  214. }
  215. else {
  216. return testProxyZone.run(testBody, applyThis);
  217. }
  218. }
  219. /**
  220. * Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
  221. * execute in a ProxyZone zone.
  222. * This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
  223. */
  224. function wrapTestInZone(testBody) {
  225. // The `done` callback is only passed through if the function expects at least one argument.
  226. // Note we have to make a function with correct number of arguments, otherwise jasmine will
  227. // think that all functions are sync or async.
  228. return (testBody &&
  229. (testBody.length
  230. ? function (done) {
  231. return runInTestZone(testBody, this, this.queueRunner, done);
  232. }
  233. : function () {
  234. return runInTestZone(testBody, this, this.queueRunner);
  235. }));
  236. }
  237. const QueueRunner = jasmine.QueueRunner;
  238. jasmine.QueueRunner = (function (_super) {
  239. __extends(ZoneQueueRunner, _super);
  240. function ZoneQueueRunner(attrs) {
  241. if (attrs.onComplete) {
  242. attrs.onComplete = ((fn) => () => {
  243. // All functions are done, clear the test zone.
  244. this.testProxyZone = null;
  245. this.testProxyZoneSpec = null;
  246. ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
  247. })(attrs.onComplete);
  248. }
  249. const nativeSetTimeout = global[Zone.__symbol__('setTimeout')];
  250. const nativeClearTimeout = global[Zone.__symbol__('clearTimeout')];
  251. if (nativeSetTimeout) {
  252. // should run setTimeout inside jasmine outside of zone
  253. attrs.timeout = {
  254. setTimeout: nativeSetTimeout ? nativeSetTimeout : global.setTimeout,
  255. clearTimeout: nativeClearTimeout ? nativeClearTimeout : global.clearTimeout,
  256. };
  257. }
  258. // create a userContext to hold the queueRunner itself
  259. // so we can access the testProxy in it/xit/beforeEach ...
  260. if (jasmine.UserContext) {
  261. if (!attrs.userContext) {
  262. attrs.userContext = new jasmine.UserContext();
  263. }
  264. attrs.userContext.queueRunner = this;
  265. }
  266. else {
  267. if (!attrs.userContext) {
  268. attrs.userContext = {};
  269. }
  270. attrs.userContext.queueRunner = this;
  271. }
  272. // patch attrs.onException
  273. const onException = attrs.onException;
  274. attrs.onException = function (error) {
  275. if (error &&
  276. error.message ===
  277. 'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
  278. // jasmine timeout, we can make the error message more
  279. // reasonable to tell what tasks are pending
  280. const proxyZoneSpec = this && this.testProxyZoneSpec;
  281. if (proxyZoneSpec) {
  282. const pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
  283. try {
  284. // try catch here in case error.message is not writable
  285. error.message += pendingTasksInfo;
  286. }
  287. catch (err) { }
  288. }
  289. }
  290. if (onException) {
  291. onException.call(this, error);
  292. }
  293. };
  294. _super.call(this, attrs);
  295. }
  296. ZoneQueueRunner.prototype.execute = function () {
  297. let zone = Zone.current;
  298. let isChildOfAmbientZone = false;
  299. while (zone) {
  300. if (zone === ambientZone) {
  301. isChildOfAmbientZone = true;
  302. break;
  303. }
  304. zone = zone.parent;
  305. }
  306. if (!isChildOfAmbientZone)
  307. throw new Error('Unexpected Zone: ' + Zone.current.name);
  308. // This is the zone which will be used for running individual tests.
  309. // It will be a proxy zone, so that the tests function can retroactively install
  310. // different zones.
  311. // Example:
  312. // - In beforeEach() do childZone = Zone.current.fork(...);
  313. // - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
  314. // zone outside of fakeAsync it will be able to escape the fakeAsync rules.
  315. // - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
  316. // fakeAsync behavior to the childZone.
  317. this.testProxyZoneSpec = new ProxyZoneSpec();
  318. this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
  319. if (!Zone.currentTask) {
  320. // if we are not running in a task then if someone would register a
  321. // element.addEventListener and then calling element.click() the
  322. // addEventListener callback would think that it is the top most task and would
  323. // drain the microtask queue on element.click() which would be incorrect.
  324. // For this reason we always force a task when running jasmine tests.
  325. Zone.current.scheduleMicroTask('jasmine.execute().forceTask', () => QueueRunner.prototype.execute.call(this));
  326. }
  327. else {
  328. _super.prototype.execute.call(this);
  329. }
  330. };
  331. return ZoneQueueRunner;
  332. })(QueueRunner);
  333. });
  334. }
  335. patchJasmine(Zone);