testing.mjs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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 test harnesses that all component harness authors should extend. This
  97. * base component harness provides the basic ability to locate element and sub-component harnesses.
  98. */
  99. class ComponentHarness {
  100. locatorFactory;
  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. *
  120. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
  121. *
  122. * ```html
  123. * <div id="d1"></div><div id="d2"></div>
  124. * ```
  125. *
  126. * then we expect:
  127. *
  128. * ```ts
  129. * await ch.locatorFor(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
  130. * await ch.locatorFor('div', DivHarness)() // Gets a `TestElement` instance for #d1
  131. * await ch.locatorFor('span')() // Throws because the `Promise` rejects
  132. * ```
  133. *
  134. * @param queries A list of queries specifying which harnesses and elements to search for:
  135. * - A `string` searches for elements matching the CSS selector specified by the string.
  136. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  137. * given class.
  138. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  139. * predicate.
  140. * @return An asynchronous locator function that searches for and returns a `Promise` for the
  141. * first element or harness matching the given search criteria. Matches are ordered first by
  142. * order in the DOM, and second by order in the queries list. If no matches are found, the
  143. * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
  144. * each query.
  145. */
  146. locatorFor(...queries) {
  147. return this.locatorFactory.locatorFor(...queries);
  148. }
  149. /**
  150. * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
  151. * or element under the host element of this `ComponentHarness`.
  152. *
  153. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
  154. *
  155. * ```html
  156. * <div id="d1"></div><div id="d2"></div>
  157. * ```
  158. *
  159. * then we expect:
  160. *
  161. * ```ts
  162. * await ch.locatorForOptional(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
  163. * await ch.locatorForOptional('div', DivHarness)() // Gets a `TestElement` instance for #d1
  164. * await ch.locatorForOptional('span')() // Gets `null`
  165. * ```
  166. *
  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 the
  174. * first element or harness matching the given search criteria. Matches are ordered first by
  175. * order in the DOM, and second by order in the queries list. If no matches are found, the
  176. * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
  177. * result types for each query or null.
  178. */
  179. locatorForOptional(...queries) {
  180. return this.locatorFactory.locatorForOptional(...queries);
  181. }
  182. /**
  183. * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
  184. * or elements under the host element of this `ComponentHarness`.
  185. *
  186. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'` and
  187. * `IdIsD1Harness.hostSelector` is `'#d1'`
  188. *
  189. * ```html
  190. * <div id="d1"></div><div id="d2"></div>
  191. * ```
  192. *
  193. * then we expect:
  194. *
  195. * ```ts
  196. * // Gets [DivHarness for #d1, TestElement for #d1, DivHarness for #d2, TestElement for #d2]
  197. * await ch.locatorForAll(DivHarness, 'div')()
  198. * // Gets [TestElement for #d1, TestElement for #d2]
  199. * await ch.locatorForAll('div', '#d1')()
  200. * // Gets [DivHarness for #d1, IdIsD1Harness for #d1, DivHarness for #d2]
  201. * await ch.locatorForAll(DivHarness, IdIsD1Harness)()
  202. * // Gets []
  203. * await ch.locatorForAll('span')()
  204. * ```
  205. *
  206. * @param queries A list of queries specifying which harnesses and elements to search for:
  207. * - A `string` searches for elements matching the CSS selector specified by the string.
  208. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  209. * given class.
  210. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  211. * predicate.
  212. * @return An asynchronous locator function that searches for and returns a `Promise` for all
  213. * elements and harnesses matching the given search criteria. Matches are ordered first by
  214. * order in the DOM, and second by order in the queries list. If an element matches more than
  215. * one `ComponentHarness` class, the locator gets an instance of each for the same element. If
  216. * an element matches multiple `string` selectors, only one `TestElement` instance is returned
  217. * for that element. The type that the `Promise` resolves to is an array where each element is
  218. * the union of all result types for each query.
  219. */
  220. locatorForAll(...queries) {
  221. return this.locatorFactory.locatorForAll(...queries);
  222. }
  223. /**
  224. * Flushes change detection and async tasks in the Angular zone.
  225. * In most cases it should not be necessary to call this manually. However, there may be some edge
  226. * cases where it is needed to fully flush animation events.
  227. */
  228. async forceStabilize() {
  229. return this.locatorFactory.forceStabilize();
  230. }
  231. /**
  232. * Waits for all scheduled or running async tasks to complete. This allows harness
  233. * authors to wait for async tasks outside of the Angular zone.
  234. */
  235. async waitForTasksOutsideAngular() {
  236. return this.locatorFactory.waitForTasksOutsideAngular();
  237. }
  238. }
  239. /**
  240. * Base class for component harnesses that authors should extend if they anticipate that consumers
  241. * of the harness may want to access other harnesses within the `<ng-content>` of the component.
  242. */
  243. class ContentContainerComponentHarness extends ComponentHarness {
  244. /**
  245. * Gets a `HarnessLoader` that searches for harnesses under the first element matching the given
  246. * selector within the current harness's content.
  247. * @param selector The selector for an element in the component's content.
  248. * @returns A `HarnessLoader` that searches for harnesses under the given selector.
  249. */
  250. async getChildLoader(selector) {
  251. return (await this.getRootHarnessLoader()).getChildLoader(selector);
  252. }
  253. /**
  254. * Gets a list of `HarnessLoader` for each element matching the given selector under the current
  255. * harness's cotnent that searches for harnesses under that element.
  256. * @param selector The selector for elements in the component's content.
  257. * @returns A list of `HarnessLoader` for each element matching the given selector.
  258. */
  259. async getAllChildLoaders(selector) {
  260. return (await this.getRootHarnessLoader()).getAllChildLoaders(selector);
  261. }
  262. /**
  263. * Gets the first matching harness for the given query within the current harness's content.
  264. * @param query The harness query to search for.
  265. * @returns The first harness matching the given query.
  266. * @throws If no matching harness is found.
  267. */
  268. async getHarness(query) {
  269. return (await this.getRootHarnessLoader()).getHarness(query);
  270. }
  271. /**
  272. * Gets the first matching harness for the given query within the current harness's content.
  273. * @param query The harness query to search for.
  274. * @returns The first harness matching the given query, or null if none is found.
  275. */
  276. async getHarnessOrNull(query) {
  277. return (await this.getRootHarnessLoader()).getHarnessOrNull(query);
  278. }
  279. /**
  280. * Gets all matching harnesses for the given query within the current harness's content.
  281. * @param query The harness query to search for.
  282. * @returns The list of harness matching the given query.
  283. */
  284. async getAllHarnesses(query) {
  285. return (await this.getRootHarnessLoader()).getAllHarnesses(query);
  286. }
  287. /**
  288. * Checks whether there is a matching harnesses for the given query within the current harness's
  289. * content.
  290. *
  291. * @param query The harness query to search for.
  292. * @returns Whetehr there is matching harnesses for the given query.
  293. */
  294. async hasHarness(query) {
  295. return (await this.getRootHarnessLoader()).hasHarness(query);
  296. }
  297. /**
  298. * Gets the root harness loader from which to start
  299. * searching for content contained by this harness.
  300. */
  301. async getRootHarnessLoader() {
  302. return this.locatorFactory.rootHarnessLoader();
  303. }
  304. }
  305. /**
  306. * A class used to associate a ComponentHarness class with predicate functions that can be used to
  307. * filter instances of the class to be matched.
  308. */
  309. class HarnessPredicate {
  310. harnessType;
  311. _predicates = [];
  312. _descriptions = [];
  313. _ancestor;
  314. constructor(harnessType, options) {
  315. this.harnessType = harnessType;
  316. this._addBaseOptions(options);
  317. }
  318. /**
  319. * Checks if the specified nullable string value matches the given pattern.
  320. * @param value The nullable string value to check, or a Promise resolving to the
  321. * nullable string value.
  322. * @param pattern The pattern the value is expected to match. If `pattern` is a string,
  323. * `value` is expected to match exactly. If `pattern` is a regex, a partial match is
  324. * allowed. If `pattern` is `null`, the value is expected to be `null`.
  325. * @return Whether the value matches the pattern.
  326. */
  327. static async stringMatches(value, pattern) {
  328. value = await value;
  329. if (pattern === null) {
  330. return value === null;
  331. }
  332. else if (value === null) {
  333. return false;
  334. }
  335. return typeof pattern === 'string' ? value === pattern : pattern.test(value);
  336. }
  337. /**
  338. * Adds a predicate function to be run against candidate harnesses.
  339. * @param description A description of this predicate that may be used in error messages.
  340. * @param predicate An async predicate function.
  341. * @return this (for method chaining).
  342. */
  343. add(description, predicate) {
  344. this._descriptions.push(description);
  345. this._predicates.push(predicate);
  346. return this;
  347. }
  348. /**
  349. * Adds a predicate function that depends on an option value to be run against candidate
  350. * harnesses. If the option value is undefined, the predicate will be ignored.
  351. * @param name The name of the option (may be used in error messages).
  352. * @param option The option value.
  353. * @param predicate The predicate function to run if the option value is not undefined.
  354. * @return this (for method chaining).
  355. */
  356. addOption(name, option, predicate) {
  357. if (option !== undefined) {
  358. this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option));
  359. }
  360. return this;
  361. }
  362. /**
  363. * Filters a list of harnesses on this predicate.
  364. * @param harnesses The list of harnesses to filter.
  365. * @return A list of harnesses that satisfy this predicate.
  366. */
  367. async filter(harnesses) {
  368. if (harnesses.length === 0) {
  369. return [];
  370. }
  371. const results = await parallel(() => harnesses.map(h => this.evaluate(h)));
  372. return harnesses.filter((_, i) => results[i]);
  373. }
  374. /**
  375. * Evaluates whether the given harness satisfies this predicate.
  376. * @param harness The harness to check
  377. * @return A promise that resolves to true if the harness satisfies this predicate,
  378. * and resolves to false otherwise.
  379. */
  380. async evaluate(harness) {
  381. const results = await parallel(() => this._predicates.map(p => p(harness)));
  382. return results.reduce((combined, current) => combined && current, true);
  383. }
  384. /** Gets a description of this predicate for use in error messages. */
  385. getDescription() {
  386. return this._descriptions.join(', ');
  387. }
  388. /** Gets the selector used to find candidate elements. */
  389. getSelector() {
  390. // We don't have to go through the extra trouble if there are no ancestors.
  391. if (!this._ancestor) {
  392. return (this.harnessType.hostSelector || '').trim();
  393. }
  394. const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor);
  395. const [selectors, selectorPlaceholders] = _splitAndEscapeSelector(this.harnessType.hostSelector || '');
  396. const result = [];
  397. // We have to add the ancestor to each part of the host compound selector, otherwise we can get
  398. // incorrect results. E.g. `.ancestor .a, .ancestor .b` vs `.ancestor .a, .b`.
  399. ancestors.forEach(escapedAncestor => {
  400. const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders);
  401. return selectors.forEach(escapedSelector => result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`));
  402. });
  403. return result.join(', ');
  404. }
  405. /** Adds base options common to all harness types. */
  406. _addBaseOptions(options) {
  407. this._ancestor = options.ancestor || '';
  408. if (this._ancestor) {
  409. this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`);
  410. }
  411. const selector = options.selector;
  412. if (selector !== undefined) {
  413. this.add(`host matches selector "${selector}"`, async (item) => {
  414. return (await item.host()).matchesSelector(selector);
  415. });
  416. }
  417. }
  418. }
  419. /** Represent a value as a string for the purpose of logging. */
  420. function _valueAsString(value) {
  421. if (value === undefined) {
  422. return 'undefined';
  423. }
  424. try {
  425. // `JSON.stringify` doesn't handle RegExp properly, so we need a custom replacer.
  426. // Use a character that is unlikely to appear in real strings to denote the start and end of
  427. // the regex. This allows us to strip out the extra quotes around the value added by
  428. // `JSON.stringify`. Also do custom escaping on `"` characters to prevent `JSON.stringify`
  429. // from escaping them as if they were part of a string.
  430. const stringifiedValue = JSON.stringify(value, (_, v) => v instanceof RegExp
  431. ? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬`
  432. : v);
  433. // Strip out the extra quotes around regexes and put back the manually escaped `"` characters.
  434. return stringifiedValue
  435. .replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '')
  436. .replace(/◬MAT_RE_ESCAPE◬/g, '"');
  437. }
  438. catch {
  439. // `JSON.stringify` will throw if the object is cyclical,
  440. // in this case the best we can do is report the value as `{...}`.
  441. return '{...}';
  442. }
  443. }
  444. /**
  445. * Splits up a compound selector into its parts and escapes any quoted content. The quoted content
  446. * has to be escaped, because it can contain commas which will throw throw us off when trying to
  447. * split it.
  448. * @param selector Selector to be split.
  449. * @returns The escaped string where any quoted content is replaced with a placeholder. E.g.
  450. * `[foo="bar"]` turns into `[foo=__cdkPlaceholder-0__]`. Use `_restoreSelector` to restore
  451. * the placeholders.
  452. */
  453. function _splitAndEscapeSelector(selector) {
  454. const placeholders = [];
  455. // Note that the regex doesn't account for nested quotes so something like `"ab'cd'e"` will be
  456. // considered as two blocks. It's a bit of an edge case, but if we find that it's a problem,
  457. // we can make it a bit smarter using a loop. Use this for now since it's more readable and
  458. // compact. More complete implementation:
  459. // https://github.com/angular/angular/blob/bd34bc9e89f18a/packages/compiler/src/shadow_css.ts#L655
  460. const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => {
  461. const replaceBy = `__cdkPlaceholder-${placeholders.length}__`;
  462. placeholders.push(keep);
  463. return replaceBy;
  464. });
  465. return [result.split(',').map(part => part.trim()), placeholders];
  466. }
  467. /** Restores a selector whose content was escaped in `_splitAndEscapeSelector`. */
  468. function _restoreSelector(selector, placeholders) {
  469. return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]);
  470. }
  471. /**
  472. * Base harness environment class that can be extended to allow `ComponentHarness`es to be used in
  473. * different test environments (e.g. testbed, protractor, etc.). This class implements the
  474. * functionality of both a `HarnessLoader` and `LocatorFactory`. This class is generic on the raw
  475. * element type, `E`, used by the particular test environment.
  476. */
  477. class HarnessEnvironment {
  478. rawRootElement;
  479. /** The root element of this `HarnessEnvironment` as a `TestElement`. */
  480. get rootElement() {
  481. this._rootElement = this._rootElement || this.createTestElement(this.rawRootElement);
  482. return this._rootElement;
  483. }
  484. set rootElement(element) {
  485. this._rootElement = element;
  486. }
  487. _rootElement;
  488. constructor(
  489. /** The native root element of this `HarnessEnvironment`. */
  490. rawRootElement) {
  491. this.rawRootElement = rawRootElement;
  492. }
  493. /** Gets a locator factory rooted at the document root. */
  494. documentRootLocatorFactory() {
  495. return this.createEnvironment(this.getDocumentRoot());
  496. }
  497. /**
  498. * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
  499. * or element under the root element of this `HarnessEnvironment`.
  500. *
  501. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
  502. *
  503. * ```html
  504. * <div id="d1"></div><div id="d2"></div>
  505. * ```
  506. *
  507. * then we expect:
  508. *
  509. * ```ts
  510. * await lf.locatorFor(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
  511. * await lf.locatorFor('div', DivHarness)() // Gets a `TestElement` instance for #d1
  512. * await lf.locatorFor('span')() // Throws because the `Promise` rejects
  513. * ```
  514. *
  515. * @param queries A list of queries specifying which harnesses and elements to search for:
  516. * - A `string` searches for elements matching the CSS selector specified by the string.
  517. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  518. * given class.
  519. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  520. * predicate.
  521. * @return An asynchronous locator function that searches for and returns a `Promise` for the
  522. * first element or harness matching the given search criteria. Matches are ordered first by
  523. * order in the DOM, and second by order in the queries list. If no matches are found, the
  524. * `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
  525. * each query.
  526. */
  527. locatorFor(...queries) {
  528. return () => _assertResultFound(this._getAllHarnessesAndTestElements(queries), _getDescriptionForLocatorForQueries(queries));
  529. }
  530. /**
  531. * Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
  532. * or element under the root element of this `HarnessEnvironmnet`.
  533. *
  534. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'`
  535. *
  536. * ```html
  537. * <div id="d1"></div><div id="d2"></div>
  538. * ```
  539. *
  540. * then we expect:
  541. *
  542. * ```ts
  543. * await lf.locatorForOptional(DivHarness, 'div')() // Gets a `DivHarness` instance for #d1
  544. * await lf.locatorForOptional('div', DivHarness)() // Gets a `TestElement` instance for #d1
  545. * await lf.locatorForOptional('span')() // Gets `null`
  546. * ```
  547. *
  548. * @param queries A list of queries specifying which harnesses and elements to search for:
  549. * - A `string` searches for elements matching the CSS selector specified by the string.
  550. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  551. * given class.
  552. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  553. * predicate.
  554. * @return An asynchronous locator function that searches for and returns a `Promise` for the
  555. * first element or harness matching the given search criteria. Matches are ordered first by
  556. * order in the DOM, and second by order in the queries list. If no matches are found, the
  557. * `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
  558. * result types for each query or null.
  559. */
  560. locatorForOptional(...queries) {
  561. return async () => (await this._getAllHarnessesAndTestElements(queries))[0] || null;
  562. }
  563. /**
  564. * Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
  565. * or elements under the root element of this `HarnessEnvironment`.
  566. *
  567. * For example, given the following DOM and assuming `DivHarness.hostSelector` is `'div'` and
  568. * `IdIsD1Harness.hostSelector` is `'#d1'`
  569. *
  570. * ```html
  571. * <div id="d1"></div><div id="d2"></div>
  572. * ```
  573. *
  574. * then we expect:
  575. *
  576. * ```ts
  577. * // Gets [DivHarness for #d1, TestElement for #d1, DivHarness for #d2, TestElement for #d2]
  578. * await lf.locatorForAll(DivHarness, 'div')()
  579. * // Gets [TestElement for #d1, TestElement for #d2]
  580. * await lf.locatorForAll('div', '#d1')()
  581. * // Gets [DivHarness for #d1, IdIsD1Harness for #d1, DivHarness for #d2]
  582. * await lf.locatorForAll(DivHarness, IdIsD1Harness)()
  583. * // Gets []
  584. * await lf.locatorForAll('span')()
  585. * ```
  586. *
  587. * @param queries A list of queries specifying which harnesses and elements to search for:
  588. * - A `string` searches for elements matching the CSS selector specified by the string.
  589. * - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
  590. * given class.
  591. * - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
  592. * predicate.
  593. * @return An asynchronous locator function that searches for and returns a `Promise` for all
  594. * elements and harnesses matching the given search criteria. Matches are ordered first by
  595. * order in the DOM, and second by order in the queries list. If an element matches more than
  596. * one `ComponentHarness` class, the locator gets an instance of each for the same element. If
  597. * an element matches multiple `string` selectors, only one `TestElement` instance is returned
  598. * for that element. The type that the `Promise` resolves to is an array where each element is
  599. * the union of all result types for each query.
  600. */
  601. locatorForAll(...queries) {
  602. return () => this._getAllHarnessesAndTestElements(queries);
  603. }
  604. /** @return A `HarnessLoader` rooted at the root element of this `HarnessEnvironment`. */
  605. async rootHarnessLoader() {
  606. return this;
  607. }
  608. /**
  609. * Gets a `HarnessLoader` instance for an element under the root of this `HarnessEnvironment`.
  610. * @param selector The selector for the root element.
  611. * @return A `HarnessLoader` rooted at the first element matching the given selector.
  612. * @throws If no matching element is found for the given selector.
  613. */
  614. async harnessLoaderFor(selector) {
  615. return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
  616. _getDescriptionForHarnessLoaderQuery(selector),
  617. ]));
  618. }
  619. /**
  620. * Gets a `HarnessLoader` instance for an element under the root of this `HarnessEnvironment`.
  621. * @param selector The selector for the root element.
  622. * @return A `HarnessLoader` rooted at the first element matching the given selector, or null if
  623. * no matching element is found.
  624. */
  625. async harnessLoaderForOptional(selector) {
  626. const elements = await this.getAllRawElements(selector);
  627. return elements[0] ? this.createEnvironment(elements[0]) : null;
  628. }
  629. /**
  630. * Gets a list of `HarnessLoader` instances, one for each matching element.
  631. * @param selector The selector for the root element.
  632. * @return A list of `HarnessLoader`, one rooted at each element matching the given selector.
  633. */
  634. async harnessLoaderForAll(selector) {
  635. const elements = await this.getAllRawElements(selector);
  636. return elements.map(element => this.createEnvironment(element));
  637. }
  638. /**
  639. * Searches for an instance of the component corresponding to the given harness type under the
  640. * `HarnessEnvironment`'s root element, and returns a `ComponentHarness` for that instance. If
  641. * multiple matching components are found, a harness for the first one is returned. If no matching
  642. * component is found, an error is thrown.
  643. * @param query A query for a harness to create
  644. * @return An instance of the given harness type
  645. * @throws If a matching component instance can't be found.
  646. */
  647. getHarness(query) {
  648. return this.locatorFor(query)();
  649. }
  650. /**
  651. * Searches for an instance of the component corresponding to the given harness type under the
  652. * `HarnessEnvironment`'s root element, and returns a `ComponentHarness` for that instance. If
  653. * multiple matching components are found, a harness for the first one is returned. If no matching
  654. * component is found, null is returned.
  655. * @param query A query for a harness to create
  656. * @return An instance of the given harness type (or null if not found).
  657. */
  658. getHarnessOrNull(query) {
  659. return this.locatorForOptional(query)();
  660. }
  661. /**
  662. * Searches for all instances of the component corresponding to the given harness type under the
  663. * `HarnessEnvironment`'s root element, and returns a list `ComponentHarness` for each instance.
  664. * @param query A query for a harness to create
  665. * @return A list instances of the given harness type.
  666. */
  667. getAllHarnesses(query) {
  668. return this.locatorForAll(query)();
  669. }
  670. /**
  671. * Searches for an instance of the component corresponding to the given harness type under the
  672. * `HarnessEnvironment`'s root element, and returns a boolean indicating if any were found.
  673. * @param query A query for a harness to create
  674. * @return A boolean indicating if an instance was found.
  675. */
  676. async hasHarness(query) {
  677. return (await this.locatorForOptional(query)()) !== null;
  678. }
  679. /**
  680. * Searches for an element with the given selector under the evironment's root element,
  681. * and returns a `HarnessLoader` rooted at the matching element. If multiple elements match the
  682. * selector, the first is used. If no elements match, an error is thrown.
  683. * @param selector The selector for the root element of the new `HarnessLoader`
  684. * @return A `HarnessLoader` rooted at the element matching the given selector.
  685. * @throws If a matching element can't be found.
  686. */
  687. async getChildLoader(selector) {
  688. return this.createEnvironment(await _assertResultFound(this.getAllRawElements(selector), [
  689. _getDescriptionForHarnessLoaderQuery(selector),
  690. ]));
  691. }
  692. /**
  693. * Searches for all elements with the given selector under the environment's root element,
  694. * and returns an array of `HarnessLoader`s, one for each matching element, rooted at that
  695. * element.
  696. * @param selector The selector for the root element of the new `HarnessLoader`
  697. * @return A list of `HarnessLoader`s, one for each matching element, rooted at that element.
  698. */
  699. async getAllChildLoaders(selector) {
  700. return (await this.getAllRawElements(selector)).map(e => this.createEnvironment(e));
  701. }
  702. /** Creates a `ComponentHarness` for the given harness type with the given raw host element. */
  703. createComponentHarness(harnessType, element) {
  704. return new harnessType(this.createEnvironment(element));
  705. }
  706. /**
  707. * Matches the given raw elements with the given list of element and harness queries to produce a
  708. * list of matched harnesses and test elements.
  709. */
  710. async _getAllHarnessesAndTestElements(queries) {
  711. if (!queries.length) {
  712. throw Error('CDK Component harness query must contain at least one element.');
  713. }
  714. const { allQueries, harnessQueries, elementQueries, harnessTypes } = _parseQueries(queries);
  715. // Combine all of the queries into one large comma-delimited selector and use it to get all raw
  716. // elements matching any of the individual queries.
  717. const rawElements = await this.getAllRawElements([...elementQueries, ...harnessQueries.map(predicate => predicate.getSelector())].join(','));
  718. // If every query is searching for the same harness subclass, we know every result corresponds
  719. // to an instance of that subclass. Likewise, if every query is for a `TestElement`, we know
  720. // every result corresponds to a `TestElement`. Otherwise we need to verify which result was
  721. // found by which selector so it can be matched to the appropriate instance.
  722. const skipSelectorCheck = (elementQueries.length === 0 && harnessTypes.size === 1) || harnessQueries.length === 0;
  723. const perElementMatches = await parallel(() => rawElements.map(async (rawElement) => {
  724. const testElement = this.createTestElement(rawElement);
  725. const allResultsForElement = await parallel(
  726. // For each query, get `null` if it doesn't match, or a `TestElement` or
  727. // `ComponentHarness` as appropriate if it does match. This gives us everything that
  728. // matches the current raw element, but it may contain duplicate entries (e.g.
  729. // multiple `TestElement` or multiple `ComponentHarness` of the same type).
  730. () => allQueries.map(query => this._getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck)));
  731. return _removeDuplicateQueryResults(allResultsForElement);
  732. }));
  733. return [].concat(...perElementMatches);
  734. }
  735. /**
  736. * Check whether the given query matches the given element, if it does return the matched
  737. * `TestElement` or `ComponentHarness`, if it does not, return null. In cases where the caller
  738. * knows for sure that the query matches the element's selector, `skipSelectorCheck` can be used
  739. * to skip verification and optimize performance.
  740. */
  741. async _getQueryResultForElement(query, rawElement, testElement, skipSelectorCheck = false) {
  742. if (typeof query === 'string') {
  743. return skipSelectorCheck || (await testElement.matchesSelector(query)) ? testElement : null;
  744. }
  745. if (skipSelectorCheck || (await testElement.matchesSelector(query.getSelector()))) {
  746. const harness = this.createComponentHarness(query.harnessType, rawElement);
  747. return (await query.evaluate(harness)) ? harness : null;
  748. }
  749. return null;
  750. }
  751. }
  752. /**
  753. * Parses a list of queries in the format accepted by the `locatorFor*` methods into an easier to
  754. * work with format.
  755. */
  756. function _parseQueries(queries) {
  757. const allQueries = [];
  758. const harnessQueries = [];
  759. const elementQueries = [];
  760. const harnessTypes = new Set();
  761. for (const query of queries) {
  762. if (typeof query === 'string') {
  763. allQueries.push(query);
  764. elementQueries.push(query);
  765. }
  766. else {
  767. const predicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
  768. allQueries.push(predicate);
  769. harnessQueries.push(predicate);
  770. harnessTypes.add(predicate.harnessType);
  771. }
  772. }
  773. return { allQueries, harnessQueries, elementQueries, harnessTypes };
  774. }
  775. /**
  776. * Removes duplicate query results for a particular element. (e.g. multiple `TestElement`
  777. * instances or multiple instances of the same `ComponentHarness` class.
  778. */
  779. async function _removeDuplicateQueryResults(results) {
  780. let testElementMatched = false;
  781. let matchedHarnessTypes = new Set();
  782. const dedupedMatches = [];
  783. for (const result of results) {
  784. if (!result) {
  785. continue;
  786. }
  787. if (result instanceof ComponentHarness) {
  788. if (!matchedHarnessTypes.has(result.constructor)) {
  789. matchedHarnessTypes.add(result.constructor);
  790. dedupedMatches.push(result);
  791. }
  792. }
  793. else if (!testElementMatched) {
  794. testElementMatched = true;
  795. dedupedMatches.push(result);
  796. }
  797. }
  798. return dedupedMatches;
  799. }
  800. /** Verifies that there is at least one result in an array. */
  801. async function _assertResultFound(results, queryDescriptions) {
  802. const result = (await results)[0];
  803. if (result == undefined) {
  804. throw Error(`Failed to find element matching one of the following queries:\n` +
  805. queryDescriptions.map(desc => `(${desc})`).join(',\n'));
  806. }
  807. return result;
  808. }
  809. /** Gets a list of description strings from a list of queries. */
  810. function _getDescriptionForLocatorForQueries(queries) {
  811. return queries.map(query => typeof query === 'string'
  812. ? _getDescriptionForTestElementQuery(query)
  813. : _getDescriptionForComponentHarnessQuery(query));
  814. }
  815. /** Gets a description string for a `ComponentHarness` query. */
  816. function _getDescriptionForComponentHarnessQuery(query) {
  817. const harnessPredicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {});
  818. const { name, hostSelector } = harnessPredicate.harnessType;
  819. const description = `${name} with host element matching selector: "${hostSelector}"`;
  820. const constraints = harnessPredicate.getDescription();
  821. return (description +
  822. (constraints ? ` satisfying the constraints: ${harnessPredicate.getDescription()}` : ''));
  823. }
  824. /** Gets a description string for a `TestElement` query. */
  825. function _getDescriptionForTestElementQuery(selector) {
  826. return `TestElement for element matching selector: "${selector}"`;
  827. }
  828. /** Gets a description string for a `HarnessLoader` query. */
  829. function _getDescriptionForHarnessLoaderQuery(selector) {
  830. return `HarnessLoader for element matching selector: "${selector}"`;
  831. }
  832. /** An enum of non-text keys that can be used with the `sendKeys` method. */
  833. // NOTE: This is a separate enum from `@angular/cdk/keycodes` because we don't necessarily want to
  834. // support every possible keyCode. We also can't rely on Protractor's `Key` because we don't want a
  835. // dependency on any particular testing framework here. Instead we'll just maintain this supported
  836. // list of keys and let individual concrete `HarnessEnvironment` classes map them to whatever key
  837. // representation is used in its respective testing framework.
  838. // tslint:disable-next-line:prefer-const-enum Seems like this causes some issues with System.js
  839. var TestKey;
  840. (function (TestKey) {
  841. TestKey[TestKey["BACKSPACE"] = 0] = "BACKSPACE";
  842. TestKey[TestKey["TAB"] = 1] = "TAB";
  843. TestKey[TestKey["ENTER"] = 2] = "ENTER";
  844. TestKey[TestKey["SHIFT"] = 3] = "SHIFT";
  845. TestKey[TestKey["CONTROL"] = 4] = "CONTROL";
  846. TestKey[TestKey["ALT"] = 5] = "ALT";
  847. TestKey[TestKey["ESCAPE"] = 6] = "ESCAPE";
  848. TestKey[TestKey["PAGE_UP"] = 7] = "PAGE_UP";
  849. TestKey[TestKey["PAGE_DOWN"] = 8] = "PAGE_DOWN";
  850. TestKey[TestKey["END"] = 9] = "END";
  851. TestKey[TestKey["HOME"] = 10] = "HOME";
  852. TestKey[TestKey["LEFT_ARROW"] = 11] = "LEFT_ARROW";
  853. TestKey[TestKey["UP_ARROW"] = 12] = "UP_ARROW";
  854. TestKey[TestKey["RIGHT_ARROW"] = 13] = "RIGHT_ARROW";
  855. TestKey[TestKey["DOWN_ARROW"] = 14] = "DOWN_ARROW";
  856. TestKey[TestKey["INSERT"] = 15] = "INSERT";
  857. TestKey[TestKey["DELETE"] = 16] = "DELETE";
  858. TestKey[TestKey["F1"] = 17] = "F1";
  859. TestKey[TestKey["F2"] = 18] = "F2";
  860. TestKey[TestKey["F3"] = 19] = "F3";
  861. TestKey[TestKey["F4"] = 20] = "F4";
  862. TestKey[TestKey["F5"] = 21] = "F5";
  863. TestKey[TestKey["F6"] = 22] = "F6";
  864. TestKey[TestKey["F7"] = 23] = "F7";
  865. TestKey[TestKey["F8"] = 24] = "F8";
  866. TestKey[TestKey["F9"] = 25] = "F9";
  867. TestKey[TestKey["F10"] = 26] = "F10";
  868. TestKey[TestKey["F11"] = 27] = "F11";
  869. TestKey[TestKey["F12"] = 28] = "F12";
  870. TestKey[TestKey["META"] = 29] = "META";
  871. TestKey[TestKey["COMMA"] = 30] = "COMMA";
  872. })(TestKey || (TestKey = {}));
  873. /**
  874. * Returns an error which reports that no keys have been specified.
  875. * @docs-private
  876. */
  877. function getNoKeysSpecifiedError() {
  878. return Error('No keys have been specified.');
  879. }
  880. /**
  881. * Gets text of element excluding certain selectors within the element.
  882. * @param element Element to get text from,
  883. * @param excludeSelector Selector identifying which elements to exclude,
  884. */
  885. function _getTextWithExcludedElements(element, excludeSelector) {
  886. const clone = element.cloneNode(true);
  887. const exclusions = clone.querySelectorAll(excludeSelector);
  888. for (let i = 0; i < exclusions.length; i++) {
  889. exclusions[i].remove();
  890. }
  891. return (clone.textContent || '').trim();
  892. }
  893. export { ComponentHarness, ContentContainerComponentHarness, HarnessEnvironment, HarnessPredicate, TestKey, _getTextWithExcludedElements, getNoKeysSpecifiedError, handleAutoChangeDetectionStatus, manualChangeDetection, parallel, stopHandlingAutoChangeDetectionStatus };
  894. //# sourceMappingURL=testing.mjs.map