Env.js 17 KB

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