testing.mjs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import { BehaviorSubject } from 'rxjs';
  2. /** Subject used to dispatch and listen for changes to the auto change detection status . */
  3. const autoChangeDetectionSubject = new BehaviorSubject({
  4. isDisabled: false,
  5. });
  6. /** The current subscription to `autoChangeDetectionSubject`. */
  7. let autoChangeDetectionSubscription;
  8. /**
  9. * The default handler for auto change detection status changes. This handler will be used if the
  10. * specific environment does not install its own.
  11. * @param status The new auto change detection status.
  12. */
  13. function defaultAutoChangeDetectionHandler(status) {
  14. status.onDetectChangesNow?.();
  15. }
  16. /**
  17. * Allows a test `HarnessEnvironment` to install its own handler for auto change detection status
  18. * changes.
  19. * @param handler The handler for the auto change detection status.
  20. */
  21. function handleAutoChangeDetectionStatus(handler) {
  22. stopHandlingAutoChangeDetectionStatus();
  23. autoChangeDetectionSubscription = autoChangeDetectionSubject.subscribe(handler);
  24. }
  25. /** Allows a `HarnessEnvironment` to stop handling auto change detection status changes. */
  26. function stopHandlingAutoChangeDetectionStatus() {
  27. autoChangeDetectionSubscription?.unsubscribe();
  28. autoChangeDetectionSubscription = null;
  29. }
  30. /**
  31. * Batches together triggering of change detection over the duration of the given function.
  32. * @param fn The function to call with batched change detection.
  33. * @param triggerBeforeAndAfter Optionally trigger change detection once before and after the batch
  34. * operation. If false, change detection will not be triggered.
  35. * @return The result of the given function.
  36. */
  37. async function batchChangeDetection(fn, triggerBeforeAndAfter) {
  38. // If change detection batching is already in progress, just run the function.
  39. if (autoChangeDetectionSubject.getValue().isDisabled) {
  40. return await fn();
  41. }
  42. // If nothing is handling change detection batching, install the default handler.
  43. if (!autoChangeDetectionSubscription) {
  44. handleAutoChangeDetectionStatus(defaultAutoChangeDetectionHandler);
  45. }
  46. if (triggerBeforeAndAfter) {
  47. await new Promise(resolve => autoChangeDetectionSubject.next({
  48. isDisabled: true,
  49. onDetectChangesNow: resolve,
  50. }));
  51. // The function passed in may throw (e.g. if the user wants to make an expectation of an error
  52. // being thrown. If this happens, we need to make sure we still re-enable change detection, so
  53. // we wrap it in a `finally` block.
  54. try {
  55. return await fn();
  56. }
  57. finally {
  58. await new Promise(resolve => autoChangeDetectionSubject.next({
  59. isDisabled: false,
  60. onDetectChangesNow: resolve,
  61. }));
  62. }
  63. }
  64. else {
  65. autoChangeDetectionSubject.next({ isDisabled: true });
  66. // The function passed in may throw (e.g. if the user wants to make an expectation of an error
  67. // being thrown. If this happens, we need to make sure we still re-enable change detection, so
  68. // we wrap it in a `finally` block.
  69. try {
  70. return await fn();
  71. }
  72. finally {
  73. autoChangeDetectionSubject.next({ isDisabled: false });
  74. }
  75. }
  76. }
  77. /**
  78. * Disables the harness system's auto change detection for the duration of the given function.
  79. * @param fn The function to disable auto change detection for.
  80. * @return The result of the given function.
  81. */
  82. async function manualChangeDetection(fn) {
  83. return batchChangeDetection(fn, false);
  84. }
  85. /**
  86. * Resolves the given list of async values in parallel (i.e. via Promise.all) while batching change
  87. * detection over the entire operation such that change detection occurs exactly once before
  88. * resolving the values and once after.
  89. * @param values A getter for the async values to resolve in parallel with batched change detection.
  90. * @return The resolved values.
  91. */
  92. async function parallel(values) {
  93. return batchChangeDetection(() => Promise.all(values()), true);
  94. }
  95. /**
  96. * Base class for component harnesses that all component harness authors should extend. This base
  97. * component harness provides the basic ability to locate element and sub-component harness. It
  98. * should be inherited when defining user's own harness.
  99. */
  100. class ComponentHarness {
  101. constructor(locatorFactory) {
  102. this.locatorFactory = locatorFactory;
  103. }
  104. /** Gets a `Promise` for the `TestElement` representing the host element of the component. */
  105. async host() {
  106. return this.locatorFactory.rootElement;
  107. }
  108. /**
  109. * Gets a `LocatorFactory` for the document root element. This factory can be used to create
  110. * locators for elements that a component creates outside of its own root element. (e.g. by
  111. * appending to document.body).
  112. */
  113. documentRootLocatorFactory() {
  114. return this.locatorFactory.documentRootLocatorFactory();
  115. }
  116. /**
  117. * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
  118. * or element under the host element of this `ComponentHarness`.
  119. * @param queries A list of queries specifying which harnesses and elements to search for:
  120. * - A `string` searches for elements matching the CSS selector specified by the string.
  121. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  122. * given class.
  123. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  124. * predicate.
  125. * @return An asynchronous locator function that searches for and returns a `Promise` for the
  126. * first element or harness matching the given search criteria. Matches are ordered first by
  127. * order in the DOM, and second by order in the queries list. If no matches are found, the
  128. * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
  129. * each query.
  130. *
  131. * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
  132. * `DivHarness.hostSelector === 'div'`:
  133. * - `await ch.locatorFor(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
  134. * - `await ch.locatorFor('div', DivHarness)()` gets a `TestElement` instance for `#d1`
  135. * - `await ch.locatorFor('span')()` throws because the `Promise` rejects.
  136. */
  137. locatorFor(...queries) {
  138. return this.locatorFactory.locatorFor(...queries);
  139. }
  140. /**
  141. * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
  142. * or element under the host element of this `ComponentHarness`.
  143. * @param queries A list of queries specifying which harnesses and elements to search for:
  144. * - A `string` searches for elements matching the CSS selector specified by the string.
  145. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  146. * given class.
  147. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  148. * predicate.
  149. * @return An asynchronous locator function that searches for and returns a `Promise` for the
  150. * first element or harness matching the given search criteria. Matches are ordered first by
  151. * order in the DOM, and second by order in the queries list. If no matches are found, the
  152. * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
  153. * result types for each query or null.
  154. *
  155. * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
  156. * `DivHarness.hostSelector === 'div'`:
  157. * - `await ch.locatorForOptional(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
  158. * - `await ch.locatorForOptional('div', DivHarness)()` gets a `TestElement` instance for `#d1`
  159. * - `await ch.locatorForOptional('span')()` gets `null`.
  160. */
  161. locatorForOptional(...queries) {
  162. return this.locatorFactory.locatorForOptional(...queries);
  163. }
  164. /**
  165. * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
  166. * or elements under the host element of this `ComponentHarness`.
  167. * @param queries A list of queries specifying which harnesses and elements to search for:
  168. * - A `string` searches for elements matching the CSS selector specified by the string.
  169. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  170. * given class.
  171. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  172. * predicate.
  173. * @return An asynchronous locator function that searches for and returns a `Promise` for all
  174. * elements and harnesses matching the given search criteria. Matches are ordered first by
  175. * order in the DOM, and second by order in the queries list. If an element matches more than
  176. * one `ComponentHarness` class, the locator gets an instance of each for the same element. If
  177. * an element matches multiple `string` selectors, only one `TestElement` instance is returned
  178. * for that element. The type that the `Promise` resolves to is an array where each element is
  179. * the union of all result types for each query.
  180. *
  181. * e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
  182. * `DivHarness.hostSelector === 'div'` and `IdIsD1Harness.hostSelector === '#d1'`:
  183. * - `await ch.locatorForAll(DivHarness, 'div')()` gets `[
  184. * DivHarness, // for #d1
  185. * TestElement, // for #d1
  186. * DivHarness, // for #d2
  187. * TestElement // for #d2
  188. * ]`
  189. * - `await ch.locatorForAll('div', '#d1')()` gets `[
  190. * TestElement, // for #d1
  191. * TestElement // for #d2
  192. * ]`
  193. * - `await ch.locatorForAll(DivHarness, IdIsD1Harness)()` gets `[
  194. * DivHarness, // for #d1
  195. * IdIsD1Harness, // for #d1
  196. * DivHarness // for #d2
  197. * ]`
  198. * - `await ch.locatorForAll('span')()` gets `[]`.
  199. */
  200. locatorForAll(...queries) {
  201. return this.locatorFactory.locatorForAll(...queries);
  202. }
  203. /**
  204. * Flushes change detection and async tasks in the Angular zone.
  205. * In most cases it should not be necessary to call this manually. However, there may be some edge
  206. * cases where it is needed to fully flush animation events.
  207. */
  208. async forceStabilize() {
  209. return this.locatorFactory.forceStabilize();
  210. }
  211. /**
  212. * Waits for all scheduled or running async tasks to complete. This allows harness
  213. * authors to wait for async tasks outside of the Angular zone.
  214. */
  215. async waitForTasksOutsideAngular() {
  216. return this.locatorFactory.waitForTasksOutsideAngular();
  217. }
  218. }
  219. /**
  220. * Base class for component harnesses that authors should extend if they anticipate that consumers
  221. * of the harness may want to access other harnesses within the `<ng-content>` of the component.
  222. */
  223. class ContentContainerComponentHarness extends ComponentHarness {
  224. async getChildLoader(selector) {
  225. return (await this.getRootHarnessLoader()).getChildLoader(selector);
  226. }
  227. async getAllChildLoaders(selector) {
  228. return (await this.getRootHarnessLoader()).getAllChildLoaders(selector);
  229. }
  230. async getHarness(query) {
  231. return (await this.getRootHarnessLoader()).getHarness(query);
  232. }
  233. async getHarnessOrNull(query) {
  234. return (await this.getRootHarnessLoader()).getHarnessOrNull(query);
  235. }
  236. async getAllHarnesses(query) {
  237. return (await this.getRootHarnessLoader()).getAllHarnesses(query);
  238. }
  239. async hasHarness(query) {
  240. return (await this.getRootHarnessLoader()).hasHarness(query);
  241. }
  242. /**
  243. * Gets the root harness loader from which to start
  244. * searching for content contained by this harness.
  245. */
  246. async getRootHarnessLoader() {
  247. return this.locatorFactory.rootHarnessLoader();
  248. }
  249. }
  250. /**
  251. * A class used to associate a ComponentHarness class with predicates functions that can be used to
  252. * filter instances of the class.
  253. */
  254. class HarnessPredicate {
  255. constructor(harnessType, options) {
  256. this.harnessType = harnessType;
  257. this._predicates = [];
  258. this._descriptions = [];
  259. this._addBaseOptions(options);
  260. }
  261. /**
  262. * Checks if the specified nullable string value matches the given pattern.
  263. * @param value The nullable string value to check, or a Promise resolving to the
  264. * nullable string value.
  265. * @param pattern The pattern the value is expected to match. If `pattern` is a string,
  266. * `value` is expected to match exactly. If `pattern` is a regex, a partial match is
  267. * allowed. If `pattern` is `null`, the value is expected to be `null`.
  268. * @return Whether the value matches the pattern.
  269. */
  270. static async stringMatches(value, pattern) {
  271. value = await value;
  272. if (pattern === null) {
  273. return value === null;
  274. }
  275. else if (value === null) {
  276. return false;
  277. }
  278. return typeof pattern === 'string' ? value === pattern : pattern.test(value);
  279. }
  280. /**
  281. * Adds a predicate function to be run against candidate harnesses.
  282. * @param description A description of this predicate that may be used in error messages.
  283. * @param predicate An async predicate function.
  284. * @return this (for method chaining).
  285. */
  286. add(description, predicate) {
  287. this._descriptions.push(description);
  288. this._predicates.push(predicate);
  289. return this;
  290. }
  291. /**
  292. * Adds a predicate function that depends on an option value to be run against candidate
  293. * harnesses. If the option value is undefined, the predicate will be ignored.
  294. * @param name The name of the option (may be used in error messages).
  295. * @param option The option value.
  296. * @param predicate The predicate function to run if the option value is not undefined.
  297. * @return this (for method chaining).
  298. */
  299. addOption(name, option, predicate) {
  300. if (option !== undefined) {
  301. this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option));
  302. }
  303. return this;
  304. }
  305. /**
  306. * Filters a list of harnesses on this predicate.
  307. * @param harnesses The list of harnesses to filter.
  308. * @return A list of harnesses that satisfy this predicate.
  309. */
  310. async filter(harnesses) {
  311. if (harnesses.length === 0) {
  312. return [];
  313. }
  314. const results = await parallel(() => harnesses.map(h => this.evaluate(h)));
  315. return harnesses.filter((_, i) => results[i]);
  316. }
  317. /**
  318. * Evaluates whether the given harness satisfies this predicate.
  319. * @param harness The harness to check
  320. * @return A promise that resolves to true if the harness satisfies this predicate,
  321. * and resolves to false otherwise.
  322. */
  323. async evaluate(harness) {
  324. const results = await parallel(() => this._predicates.map(p => p(harness)));
  325. return results.reduce((combined, current) => combined && current, true);
  326. }
  327. /** Gets a description of this predicate for use in error messages. */
  328. getDescription() {
  329. return this._descriptions.join(', ');
  330. }
  331. /** Gets the selector used to find candidate elements. */
  332. getSelector() {
  333. // We don't have to go through the extra trouble if there are no ancestors.
  334. if (!this._ancestor) {
  335. return (this.harnessType.hostSelector || '').trim();
  336. }
  337. const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor);
  338. const [selectors, selectorPlaceholders] = _splitAndEscapeSelector(this.harnessType.hostSelector || '');
  339. const result = [];
  340. // We have to add the ancestor to each part of the host compound selector, otherwise we can get
  341. // incorrect results. E.g. `.ancestor .a, .ancestor .b` vs `.ancestor .a, .b`.
  342. ancestors.forEach(escapedAncestor => {
  343. const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders);
  344. return selectors.forEach(escapedSelector => result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`));
  345. });
  346. return result.join(', ');
  347. }
  348. /** Adds base options common to all harness types. */
  349. _addBaseOptions(options) {
  350. this._ancestor = options.ancestor || '';
  351. if (this._ancestor) {
  352. this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`);
  353. }
  354. const selector = options.selector;
  355. if (selector !== undefined) {
  356. this.add(`host matches selector "${selector}"`, async (item) => {
  357. return (await item.host()).matchesSelector(selector);
  358. });
  359. }
  360. }
  361. }
  362. /** Represent a value as a string for the purpose of logging. */
  363. function _valueAsString(value) {
  364. if (value === undefined) {
  365. return 'undefined';
  366. }
  367. try {
  368. // `JSON.stringify` doesn't handle RegExp properly, so we need a custom replacer.
  369. // Use a character that is unlikely to appear in real strings to denote the start and end of
  370. // the regex. This allows us to strip out the extra quotes around the value added by
  371. // `JSON.stringify`. Also do custom escaping on `"` characters to prevent `JSON.stringify`
  372. // from escaping them as if they were part of a string.
  373. const stringifiedValue = JSON.stringify(value, (_, v) => v instanceof RegExp
  374. ? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬`
  375. : v);
  376. // Strip out the extra quotes around regexes and put back the manually escaped `"` characters.
  377. return stringifiedValue
  378. .replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '')
  379. .replace(/◬MAT_RE_ESCAPE◬/g, '"');
  380. }
  381. catch {
  382. // `JSON.stringify` will throw if the object is cyclical,
  383. // in this case the best we can do is report the value as `{...}`.
  384. return '{...}';
  385. }
  386. }
  387. /**
  388. * Splits up a compound selector into its parts and escapes any quoted content. The quoted content
  389. * has to be escaped, because it can contain commas which will throw throw us off when trying to
  390. * split it.
  391. * @param selector Selector to be split.
  392. * @returns The escaped string where any quoted content is replaced with a placeholder. E.g.
  393. * `[foo="bar"]` turns into `[foo=__cdkPlaceholder-0__]`. Use `_restoreSelector` to restore
  394. * the placeholders.
  395. */
  396. function _splitAndEscapeSelector(selector) {
  397. const placeholders = [];
  398. // Note that the regex doesn't account for nested quotes so something like `"ab'cd'e"` will be
  399. // considered as two blocks. It's a bit of an edge case, but if we find that it's a problem,
  400. // we can make it a bit smarter using a loop. Use this for now since it's more readable and
  401. // compact. More complete implementation:
  402. // https://github.com/angular/angular/blob/bd34bc9e89f18a/packages/compiler/src/shadow_css.ts#L655
  403. const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => {
  404. const replaceBy = `__cdkPlaceholder-${placeholders.length}__`;
  405. placeholders.push(keep);
  406. return replaceBy;
  407. });
  408. return [result.split(',').map(part => part.trim()), placeholders];
  409. }
  410. /** Restores a selector whose content was escaped in `_splitAndEscapeSelector`. */
  411. function _restoreSelector(selector, placeholders) {
  412. return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]);
  413. }
  414. /**
  415. * Base harness environment class that can be extended to allow `ComponentHarness`es to be used in
  416. * different test environments (e.g. testbed, protractor, etc.). This class implements the
  417. * functionality of both a `HarnessLoader` and `LocatorFactory`. This class is generic on the raw
  418. * element type, `E`, used by the particular test environment.
  419. */
  420. class HarnessEnvironment {
  421. // Implemented as part of the `LocatorFactory` interface.
  422. get rootElement() {
  423. this._rootElement = this._rootElement || this.createTestElement(this.rawRootElement);
  424. return this._rootElement;
  425. }
  426. set rootElement(element) {
  427. this._rootElement = element;
  428. }
  429. constructor(rawRootElement) {
  430. this.rawRootElement = rawRootElement;
  431. }
  432. // Implemented as part of the `LocatorFactory` interface.
  433. documentRootLocatorFactory() {
  434. return this.createEnvironment(this.getDocumentRoot());
  435. }
  436. // Implemented as part of the `LocatorFactory` interface.
  437. locatorFor(...queries) {
  438. return () => _assertResultFound(this._getAllHarnessesAndTestElements(queries), _getDescriptionForLocatorForQueries(queries));
  439. }
  440. // Implemented as part of the `LocatorFactory` interface.
  441. locatorForOptional(...queries) {
  442. return async () => (await this._getAllHarnessesAndTestElements(queries))[0] || null;
  443. }
  444. // Implemented as part of the `LocatorFactory` interface.
  445. locatorForAll(...queries) {
  446. return () => this._getAllHarnessesAndTestElements(queries);
  447. }
  448. // Implemented as part of the `LocatorFactory` interface.
  449. async rootHarnessLoader() {
  450. return this;
  451. }
  452. // Implemented as part of the `LocatorFactory` interface.
  453. async harnessLoaderFor(selector) {
  454. return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
  455. _getDescriptionForHarnessLoaderQuery(selector),
  456. ]));
  457. }
  458. // Implemented as part of the `LocatorFactory` interface.
  459. async harnessLoaderForOptional(selector) {
  460. const elements = await this.getAllRawElements(selector);
  461. return elements[0] ? this.createEnvironment(elements[0]) : null;
  462. }
  463. // Implemented as part of the `LocatorFactory` interface.
  464. async harnessLoaderForAll(selector) {
  465. const elements = await this.getAllRawElements(selector);
  466. return elements.map(element => this.createEnvironment(element));
  467. }
  468. // Implemented as part of the `HarnessLoader` interface.
  469. getHarness(query) {
  470. return this.locatorFor(query)();
  471. }
  472. // Implemented as part of the `HarnessLoader` interface.
  473. getHarnessOrNull(query) {
  474. return this.locatorForOptional(query)();
  475. }
  476. // Implemented as part of the `HarnessLoader` interface.
  477. getAllHarnesses(query) {
  478. return this.locatorForAll(query)();
  479. }
  480. // Implemented as part of the `HarnessLoader` interface.
  481. async hasHarness(query) {
  482. return (await this.locatorForOptional(query)()) !== null;
  483. }
  484. // Implemented as part of the `HarnessLoader` interface.
  485. async getChildLoader(selector) {
  486. return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
  487. _getDescriptionForHarnessLoaderQuery(selector),
  488. ]));
  489. }
  490. // Implemented as part of the `HarnessLoader` interface.
  491. async getAllChildLoaders(selector) {
  492. return (await this.getAllRawElements(selector)).map(e => this.createEnvironment(e));
  493. }
  494. /** Creates a `ComponentHarness` for the given harness type with the given raw host element. */
  495. createComponentHarness(harnessType, element) {
  496. return new harnessType(this.createEnvironment(element));
  497. }
  498. /**
  499. * Matches the given raw elements with the given list of element and harness queries to produce a
  500. * list of matched harnesses and test elements.
  501. */
  502. async _getAllHarnessesAndTestElements(queries) {
  503. if (!queries.length) {
  504. throw Error('CDK Component harness query must contain at least one element.');
  505. }
  506. const { allQueries, harnessQueries, elementQueries, harnessTypes } = _parseQueries(queries);
  507. // Combine all of the queries into one large comma-delimited selector and use it to get all raw
  508. // elements matching any of the individual queries.
  509. const rawElements = await this.getAllRawElements([...elementQueries, ...harnessQueries.map(predicate => predicate.getSelector())].join(','));
  510. // If every query is searching for the same harness subclass, we know every result corresponds
  511. // to an instance of that subclass. Likewise, if every query is for a `TestElement`, we know
  512. // every result corresponds to a `TestElement`. Otherwise we need to verify which result was
  513. // found by which selector so it can be matched to the appropriate instance.
  514. const skipSelectorCheck = (elementQueries.length === 0 && harnessTypes.size === 1) || harnessQueries.length === 0;
  515. const perElementMatches = await parallel(() => rawElements.map(async (rawElement) => {
  516. const testElement = this.createTestElement(rawElement);
  517. const allResultsForElement = await parallel(
  518. // For each query, get `null` if it doesn't match, or a `TestElement` or
  519. // `ComponentHarness` as appropriate if it does match. This gives us everything that
  520. // matches the current raw element, but it may contain duplicate entries (e.g.
  521. // multiple `TestElement` or multiple `ComponentHarness` of the same type).
  522. () => allQueries.map(query => this._getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck)));
  523. return _removeDuplicateQueryResults(allResultsForElement);
  524. }));
  525. return [].concat(...perElementMatches);
  526. }
  527. /**
  528. * Check whether the given query matches the given element, if it does return the matched
  529. * `TestElement` or `ComponentHarness`, if it does not, return null. In cases where the caller
  530. * knows for sure that the query matches the element's selector, `skipSelectorCheck` can be used
  531. * to skip verification and optimize performance.
  532. */
  533. async _getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck = false) {
  534. if (typeof query === 'string') {
  535. return skipSelectorCheck || (await testElement.matchesSelector(query)) ? testElement : null;
  536. }
  537. if (skipSelectorCheck || (await testElement.matchesSelector(query.getSelector()))) {
  538. const harness = this.createComponentHarness(query.harnessType, rawElement);
  539. return (await query.evaluate(harness)) ? harness : null;
  540. }
  541. return null;
  542. }
  543. }
  544. /**
  545. * Parses a list of queries in the format accepted by the `locatorFor*` methods into an easier to
  546. * work with format.
  547. */
  548. function _parseQueries(queries) {
  549. const allQueries = [];
  550. const harnessQueries = [];
  551. const elementQueries = [];
  552. const harnessTypes = new Set();
  553. for (const query of queries) {
  554. if (typeof query === 'string') {
  555. allQueries.push(query);
  556. elementQueries.push(query);
  557. }
  558. else {
  559. const predicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
  560. allQueries.push(predicate);
  561. harnessQueries.push(predicate);
  562. harnessTypes.add(predicate.harnessType);
  563. }
  564. }
  565. return { allQueries, harnessQueries, elementQueries, harnessTypes };
  566. }
  567. /**
  568. * Removes duplicate query results for a particular element. (e.g. multiple `TestElement`
  569. * instances or multiple instances of the same `ComponentHarness` class.
  570. */
  571. async function _removeDuplicateQueryResults(results) {
  572. let testElementMatched = false;
  573. let matchedHarnessTypes = new Set();
  574. const dedupedMatches = [];
  575. for (const result of results) {
  576. if (!result) {
  577. continue;
  578. }
  579. if (result instanceof ComponentHarness) {
  580. if (!matchedHarnessTypes.has(result.constructor)) {
  581. matchedHarnessTypes.add(result.constructor);
  582. dedupedMatches.push(result);
  583. }
  584. }
  585. else if (!testElementMatched) {
  586. testElementMatched = true;
  587. dedupedMatches.push(result);
  588. }
  589. }
  590. return dedupedMatches;
  591. }
  592. /** Verifies that there is at least one result in an array. */
  593. async function _assertResultFound(results, queryDescriptions) {
  594. const result = (await results)[0];
  595. if (result == undefined) {
  596. throw Error(`Failed to find element matching one of the following queries:\n` +
  597. queryDescriptions.map(desc => `(${desc})`).join(',\n'));
  598. }
  599. return result;
  600. }
  601. /** Gets a list of description strings from a list of queries. */
  602. function _getDescriptionForLocatorForQueries(queries) {
  603. return queries.map(query => typeof query === 'string'
  604. ? _getDescriptionForTestElementQuery(query)
  605. : _getDescriptionForComponentHarnessQuery(query));
  606. }
  607. /** Gets a description string for a `ComponentHarness` query. */
  608. function _getDescriptionForComponentHarnessQuery(query) {
  609. const harnessPredicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
  610. const { name, hostSelector } = harnessPredicate.harnessType;
  611. const description = `${name} with host element matching selector: "${hostSelector}"`;
  612. const constraints = harnessPredicate.getDescription();
  613. return (description +
  614. (constraints ? ` satisfying the constraints: ${harnessPredicate.getDescription()}` : ''));
  615. }
  616. /** Gets a description string for a `TestElement` query. */
  617. function _getDescriptionForTestElementQuery(selector) {
  618. return `TestElement for element matching selector: "${selector}"`;
  619. }
  620. /** Gets a description string for a `HarnessLoader` query. */
  621. function _getDescriptionForHarnessLoaderQuery(selector) {
  622. return `HarnessLoader for element matching selector: "${selector}"`;
  623. }
  624. /** An enum of non-text keys that can be used with the `sendKeys` method. */
  625. // NOTE: This is a separate enum from `@angular/cdk/keycodes` because we don't necessarily want to
  626. // support every possible keyCode. We also can't rely on Protractor's `Key` because we don't want a
  627. // dependency on any particular testing framework here. Instead we'll just maintain this supported
  628. // list of keys and let individual concrete `HarnessEnvironment` classes map them to whatever key
  629. // representation is used in its respective testing framework.
  630. // tslint:disable-next-line:prefer-const-enum Seems like this causes some issues with System.js
  631. var TestKey;
  632. (function (TestKey) {
  633. TestKey[TestKey["BACKSPACE"] = 0] = "BACKSPACE";
  634. TestKey[TestKey["TAB"] = 1] = "TAB";
  635. TestKey[TestKey["ENTER"] = 2] = "ENTER";
  636. TestKey[TestKey["SHIFT"] = 3] = "SHIFT";
  637. TestKey[TestKey["CONTROL"] = 4] = "CONTROL";
  638. TestKey[TestKey["ALT"] = 5] = "ALT";
  639. TestKey[TestKey["ESCAPE"] = 6] = "ESCAPE";
  640. TestKey[TestKey["PAGE_UP"] = 7] = "PAGE_UP";
  641. TestKey[TestKey["PAGE_DOWN"] = 8] = "PAGE_DOWN";
  642. TestKey[TestKey["END"] = 9] = "END";
  643. TestKey[TestKey["HOME"] = 10] = "HOME";
  644. TestKey[TestKey["LEFT_ARROW"] = 11] = "LEFT_ARROW";
  645. TestKey[TestKey["UP_ARROW"] = 12] = "UP_ARROW";
  646. TestKey[TestKey["RIGHT_ARROW"] = 13] = "RIGHT_ARROW";
  647. TestKey[TestKey["DOWN_ARROW"] = 14] = "DOWN_ARROW";
  648. TestKey[TestKey["INSERT"] = 15] = "INSERT";
  649. TestKey[TestKey["DELETE"] = 16] = "DELETE";
  650. TestKey[TestKey["F1"] = 17] = "F1";
  651. TestKey[TestKey["F2"] = 18] = "F2";
  652. TestKey[TestKey["F3"] = 19] = "F3";
  653. TestKey[TestKey["F4"] = 20] = "F4";
  654. TestKey[TestKey["F5"] = 21] = "F5";
  655. TestKey[TestKey["F6"] = 22] = "F6";
  656. TestKey[TestKey["F7"] = 23] = "F7";
  657. TestKey[TestKey["F8"] = 24] = "F8";
  658. TestKey[TestKey["F9"] = 25] = "F9";
  659. TestKey[TestKey["F10"] = 26] = "F10";
  660. TestKey[TestKey["F11"] = 27] = "F11";
  661. TestKey[TestKey["F12"] = 28] = "F12";
  662. TestKey[TestKey["META"] = 29] = "META";
  663. })(TestKey || (TestKey = {}));
  664. /**
  665. * Returns an error which reports that no keys have been specified.
  666. * @docs-private
  667. */
  668. function getNoKeysSpecifiedError() {
  669. return Error('No keys have been specified.');
  670. }
  671. /**
  672. * Gets text of element excluding certain selectors within the element.
  673. * @param element Element to get text from,
  674. * @param excludeSelector Selector identifying which elements to exclude,
  675. */
  676. function _getTextWithExcludedElements(element, excludeSelector) {
  677. const clone = element.cloneNode(true);
  678. const exclusions = clone.querySelectorAll(excludeSelector);
  679. for (let i = 0; i < exclusions.length; i++) {
  680. exclusions[i].remove();
  681. }
  682. return (clone.textContent || '').trim();
  683. }
  684. export { ComponentHarness, ContentContainerComponentHarness, HarnessEnvironment, HarnessPredicate, TestKey, _getTextWithExcludedElements, getNoKeysSpecifiedError, handleAutoChangeDetectionStatus, manualChangeDetection, parallel, stopHandlingAutoChangeDetectionStatus };
  685. //# sourceMappingURL=testing.mjs.map