Env.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = function (j$) {
  6. function Env(options) {
  7. options = options || {};
  8. const self = this;
  9. let totalSpecsDefined = 0;
  10. let catchExceptions = true;
  11. const realSetTimeout = global.setTimeout;
  12. const realClearTimeout = global.clearTimeout;
  13. const runnableResources = {};
  14. let currentSpec = null;
  15. const currentlyExecutingSuites = [];
  16. let currentDeclarationSuite = null;
  17. let throwOnExpectationFailure = false;
  18. let random = false;
  19. let seed = null;
  20. const currentSuite = function () {
  21. return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
  22. };
  23. const currentRunnable = function () {
  24. return currentSpec || currentSuite();
  25. };
  26. const reporter = new j$.ReportDispatcher(['jasmineStarted', 'jasmineDone', 'suiteStarted', 'suiteDone', 'specStarted', 'specDone']);
  27. this.specFilter = function () {
  28. return true;
  29. };
  30. let nextSpecId = 0;
  31. const getNextSpecId = function () {
  32. return 'spec' + nextSpecId++;
  33. };
  34. let nextSuiteId = 0;
  35. const getNextSuiteId = function () {
  36. return 'suite' + nextSuiteId++;
  37. };
  38. const defaultResourcesForRunnable = function (id, parentRunnableId) {
  39. const resources = { spies: [] };
  40. runnableResources[id] = resources;
  41. };
  42. const clearResourcesForRunnable = function (id) {
  43. spyRegistry.clearSpies();
  44. delete runnableResources[id];
  45. };
  46. const beforeAndAfterFns = function (suite) {
  47. return function () {
  48. let afters = [];
  49. let befores = [];
  50. while (suite) {
  51. befores = befores.concat(suite.beforeFns);
  52. afters = afters.concat(suite.afterFns);
  53. suite = suite.parentSuite;
  54. }
  55. return {
  56. befores: befores.reverse(),
  57. afters
  58. };
  59. };
  60. };
  61. const getSpecName = function (spec, suite) {
  62. const fullName = [spec.description];
  63. const suiteFullName = suite.getFullName();
  64. if (suiteFullName !== '') {
  65. fullName.unshift(suiteFullName);
  66. }
  67. return fullName.join(' ');
  68. };
  69. this.catchExceptions = function (value) {
  70. catchExceptions = !!value;
  71. return catchExceptions;
  72. };
  73. this.catchingExceptions = function () {
  74. return catchExceptions;
  75. };
  76. this.throwOnExpectationFailure = function (value) {
  77. throwOnExpectationFailure = !!value;
  78. };
  79. this.throwingExpectationFailures = function () {
  80. return throwOnExpectationFailure;
  81. };
  82. this.randomizeTests = function (value) {
  83. random = !!value;
  84. };
  85. this.randomTests = function () {
  86. return random;
  87. };
  88. this.seed = function (value) {
  89. if (value) {
  90. seed = value;
  91. }
  92. return seed;
  93. };
  94. function queueRunnerFactory(options) {
  95. options.clearTimeout = realClearTimeout;
  96. options.fail = self.fail;
  97. options.setTimeout = realSetTimeout;
  98. return (0, _queue_runner2.default)(options);
  99. }
  100. const topSuite = new j$.Suite({
  101. id: getNextSuiteId(),
  102. getTestPath() {
  103. return j$.testPath;
  104. }
  105. });
  106. defaultResourcesForRunnable(topSuite.id);
  107. currentDeclarationSuite = topSuite;
  108. this.topSuite = function () {
  109. return topSuite;
  110. };
  111. this.execute = (() => {
  112. var _ref = _asyncToGenerator(function* (runnablesToRun) {
  113. if (!runnablesToRun) {
  114. if (focusedRunnables.length) {
  115. runnablesToRun = focusedRunnables;
  116. } else {
  117. runnablesToRun = [topSuite.id];
  118. }
  119. }
  120. const uncaught = function (err) {
  121. if (currentSpec) {
  122. currentSpec.onException(err);
  123. currentSpec.cancel();
  124. } else {
  125. console.error('Unhandled error');
  126. console.error(err.stack);
  127. }
  128. };
  129. // Need to ensure we are the only ones handling these exceptions.
  130. const oldListenersException = process.listeners('uncaughtException').slice();
  131. const oldListenersRejection = process.listeners('unhandledRejection').slice();
  132. j$.process.removeAllListeners('uncaughtException');
  133. j$.process.removeAllListeners('unhandledRejection');
  134. j$.process.on('uncaughtException', uncaught);
  135. j$.process.on('unhandledRejection', uncaught);
  136. reporter.jasmineStarted({ totalSpecsDefined });
  137. currentlyExecutingSuites.push(topSuite);
  138. yield (0, _tree_processor2.default)({
  139. nodeComplete(suite) {
  140. if (!suite.disabled) {
  141. clearResourcesForRunnable(suite.id);
  142. }
  143. currentlyExecutingSuites.pop();
  144. reporter.suiteDone(suite.getResult());
  145. },
  146. nodeStart(suite) {
  147. currentlyExecutingSuites.push(suite);
  148. defaultResourcesForRunnable(suite.id, suite.parentSuite.id);
  149. reporter.suiteStarted(suite.result);
  150. },
  151. queueRunnerFactory,
  152. runnableIds: runnablesToRun,
  153. tree: topSuite
  154. });
  155. clearResourcesForRunnable(topSuite.id);
  156. currentlyExecutingSuites.pop();
  157. reporter.jasmineDone({
  158. failedExpectations: topSuite.result.failedExpectations
  159. });
  160. j$.process.removeListener('uncaughtException', uncaught);
  161. j$.process.removeListener('unhandledRejection', uncaught);
  162. // restore previous exception handlers
  163. oldListenersException.forEach(function (listener) {
  164. j$.process.on('uncaughtException', listener);
  165. });
  166. oldListenersRejection.forEach(function (listener) {
  167. j$.process.on('unhandledRejection', listener);
  168. });
  169. });
  170. return function (_x) {
  171. return _ref.apply(this, arguments);
  172. };
  173. })();
  174. this.addReporter = function (reporterToAdd) {
  175. reporter.addReporter(reporterToAdd);
  176. };
  177. this.provideFallbackReporter = function (reporterToAdd) {
  178. reporter.provideFallbackReporter(reporterToAdd);
  179. };
  180. this.clearReporters = function () {
  181. reporter.clearReporters();
  182. };
  183. const spyRegistry = new j$.SpyRegistry({
  184. currentSpies() {
  185. if (!currentRunnable()) {
  186. throw new Error('Spies must be created in a before function or a spec');
  187. }
  188. return runnableResources[currentRunnable().id].spies;
  189. }
  190. });
  191. this.allowRespy = function (allow) {
  192. spyRegistry.allowRespy(allow);
  193. };
  194. this.spyOn = function () {
  195. return spyRegistry.spyOn.apply(spyRegistry, arguments);
  196. };
  197. const suiteFactory = function (description) {
  198. const suite = new j$.Suite({
  199. id: getNextSuiteId(),
  200. description,
  201. parentSuite: currentDeclarationSuite,
  202. throwOnExpectationFailure,
  203. getTestPath() {
  204. return j$.testPath;
  205. }
  206. });
  207. return suite;
  208. };
  209. this.describe = function (description, specDefinitions) {
  210. const suite = suiteFactory(description);
  211. if (specDefinitions.length > 0) {
  212. throw new Error('describe does not expect any arguments');
  213. }
  214. if (currentDeclarationSuite.markedPending) {
  215. suite.pend();
  216. }
  217. addSpecsToSuite(suite, specDefinitions);
  218. return suite;
  219. };
  220. this.xdescribe = function (description, specDefinitions) {
  221. const suite = suiteFactory(description);
  222. suite.pend();
  223. addSpecsToSuite(suite, specDefinitions);
  224. return suite;
  225. };
  226. const focusedRunnables = [];
  227. this.fdescribe = function (description, specDefinitions) {
  228. const suite = suiteFactory(description);
  229. suite.isFocused = true;
  230. focusedRunnables.push(suite.id);
  231. unfocusAncestor();
  232. addSpecsToSuite(suite, specDefinitions);
  233. return suite;
  234. };
  235. function addSpecsToSuite(suite, specDefinitions) {
  236. const parentSuite = currentDeclarationSuite;
  237. parentSuite.addChild(suite);
  238. currentDeclarationSuite = suite;
  239. let declarationError = null;
  240. try {
  241. specDefinitions.call(suite);
  242. } catch (e) {
  243. declarationError = e;
  244. }
  245. if (declarationError) {
  246. self.it('encountered a declaration exception', () => {
  247. throw declarationError;
  248. });
  249. }
  250. currentDeclarationSuite = parentSuite;
  251. }
  252. function findFocusedAncestor(suite) {
  253. while (suite) {
  254. if (suite.isFocused) {
  255. return suite.id;
  256. }
  257. suite = suite.parentSuite;
  258. }
  259. return null;
  260. }
  261. function unfocusAncestor() {
  262. const focusedAncestor = findFocusedAncestor(currentDeclarationSuite);
  263. if (focusedAncestor) {
  264. for (let i = 0; i < focusedRunnables.length; i++) {
  265. if (focusedRunnables[i] === focusedAncestor) {
  266. focusedRunnables.splice(i, 1);
  267. break;
  268. }
  269. }
  270. }
  271. }
  272. const specFactory = function (description, fn, suite, timeout) {
  273. totalSpecsDefined++;
  274. const spec = new j$.Spec({
  275. id: getNextSpecId(),
  276. beforeAndAfterFns: beforeAndAfterFns(suite),
  277. resultCallback: specResultCallback,
  278. getSpecName(spec) {
  279. return getSpecName(spec, suite);
  280. },
  281. getTestPath() {
  282. return j$.testPath;
  283. },
  284. onStart: specStarted,
  285. description,
  286. queueRunnerFactory,
  287. userContext() {
  288. return suite.clonedSharedUserContext();
  289. },
  290. queueableFn: {
  291. fn,
  292. timeout() {
  293. return timeout || j$.DEFAULT_TIMEOUT_INTERVAL;
  294. }
  295. },
  296. throwOnExpectationFailure
  297. });
  298. if (!self.specFilter(spec)) {
  299. spec.disable();
  300. }
  301. return spec;
  302. function specResultCallback(result) {
  303. clearResourcesForRunnable(spec.id);
  304. currentSpec = null;
  305. reporter.specDone(result);
  306. }
  307. function specStarted(spec) {
  308. currentSpec = spec;
  309. defaultResourcesForRunnable(spec.id, suite.id);
  310. reporter.specStarted(spec.result);
  311. }
  312. };
  313. this.it = function (description, fn, timeout) {
  314. const spec = specFactory(description, fn, currentDeclarationSuite, timeout);
  315. if (currentDeclarationSuite.markedPending) {
  316. spec.pend();
  317. }
  318. // When a test is defined inside another, jasmine will not run it.
  319. // This check throws an error to warn the user about the edge-case.
  320. if (currentSpec !== null) {
  321. throw new Error('Tests cannot be nested. Test `' + spec.description + '` cannot run because it is nested within `' + currentSpec.description + '`.');
  322. }
  323. currentDeclarationSuite.addChild(spec);
  324. return spec;
  325. };
  326. this.xit = function () {
  327. const spec = this.it.apply(this, arguments);
  328. spec.pend('Temporarily disabled with xit');
  329. return spec;
  330. };
  331. this.fit = function (description, fn, timeout) {
  332. const spec = specFactory(description, fn, currentDeclarationSuite, timeout);
  333. currentDeclarationSuite.addChild(spec);
  334. focusedRunnables.push(spec.id);
  335. unfocusAncestor();
  336. return spec;
  337. };
  338. this.beforeEach = function (beforeEachFunction, timeout) {
  339. currentDeclarationSuite.beforeEach({
  340. fn: beforeEachFunction,
  341. timeout() {
  342. return timeout || j$.DEFAULT_TIMEOUT_INTERVAL;
  343. }
  344. });
  345. };
  346. this.beforeAll = function (beforeAllFunction, timeout) {
  347. currentDeclarationSuite.beforeAll({
  348. fn: beforeAllFunction,
  349. timeout() {
  350. return timeout || j$.DEFAULT_TIMEOUT_INTERVAL;
  351. }
  352. });
  353. };
  354. this.afterEach = function (afterEachFunction, timeout) {
  355. currentDeclarationSuite.afterEach({
  356. fn: afterEachFunction,
  357. timeout() {
  358. return timeout || j$.DEFAULT_TIMEOUT_INTERVAL;
  359. }
  360. });
  361. };
  362. this.afterAll = function (afterAllFunction, timeout) {
  363. currentDeclarationSuite.afterAll({
  364. fn: afterAllFunction,
  365. timeout() {
  366. return timeout || j$.DEFAULT_TIMEOUT_INTERVAL;
  367. }
  368. });
  369. };
  370. this.pending = function (message) {
  371. let fullMessage = j$.Spec.pendingSpecExceptionMessage;
  372. if (message) {
  373. fullMessage += message;
  374. }
  375. throw fullMessage;
  376. };
  377. this.fail = function (error) {
  378. let message = 'Failed';
  379. if (error) {
  380. message += ': ';
  381. message += error.message || error;
  382. }
  383. currentRunnable().addExpectationResult(false, {
  384. matcherName: '',
  385. passed: false,
  386. expected: '',
  387. actual: '',
  388. message,
  389. error: error && error.message ? error : null
  390. });
  391. };
  392. }
  393. return Env;
  394. };
  395. var _queue_runner = require('../queue_runner');
  396. var _queue_runner2 = _interopRequireDefault(_queue_runner);
  397. var _tree_processor = require('../tree_processor');
  398. var _tree_processor2 = _interopRequireDefault(_tree_processor);
  399. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  400. function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /**
  401. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  402. *
  403. * This source code is licensed under the MIT license found in the
  404. * LICENSE file in the root directory of this source tree.
  405. *
  406. */
  407. // This file is a heavily modified fork of Jasmine. Original license:
  408. /*
  409. Copyright (c) 2008-2016 Pivotal Labs
  410. Permission is hereby granted, free of charge, to any person obtaining
  411. a copy of this software and associated documentation files (the
  412. "Software"), to deal in the Software without restriction, including
  413. without limitation the rights to use, copy, modify, merge, publish,
  414. distribute, sublicense, and/or sell copies of the Software, and to
  415. permit persons to whom the Software is furnished to do so, subject to
  416. the following conditions:
  417. The above copyright notice and this permission notice shall be
  418. included in all copies or substantial portions of the Software.
  419. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  420. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  421. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  422. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  423. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  424. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  425. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  426. */
  427. /* eslint-disable sort-keys */
  428. // Try getting the real promise object from the context, if available. Someone
  429. // could have overridden it in a test. Async functions return it implicitly.
  430. // eslint-disable-next-line no-unused-vars
  431. const Promise = global[Symbol.for('jest-native-promise')] || global.Promise;