jasmine-patch.js 14 KB

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