jasmine.ts 13 KB

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