-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathcomponent-harness.ts
685 lines (622 loc) · 30.5 KB
/
component-harness.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {parallel} from './change-detection';
import {TestElement} from './test-element';
/** An async function that returns a promise when called. */
export type AsyncFactoryFn<T> = () => Promise<T>;
/** An async function that takes an item and returns a boolean promise */
export type AsyncPredicate<T> = (item: T) => Promise<boolean>;
/** An async function that takes an item and an option value and returns a boolean promise. */
export type AsyncOptionPredicate<T, O> = (item: T, option: O) => Promise<boolean>;
/**
* A query for a `ComponentHarness`, which is expressed as either a `ComponentHarnessConstructor` or
* a `HarnessPredicate`.
*/
export type HarnessQuery<T extends ComponentHarness> =
| ComponentHarnessConstructor<T>
| HarnessPredicate<T>;
/**
* The result type obtained when searching using a particular list of queries. This type depends on
* the particular items being queried.
* - If one of the queries is for a `ComponentHarnessConstructor<C1>`, it means that the result
* might be a harness of type `C1`
* - If one of the queries is for a `HarnessPredicate<C2>`, it means that the result might be a
* harness of type `C2`
* - If one of the queries is for a `string`, it means that the result might be a `TestElement`.
*
* Since we don't know for sure which query will match, the result type if the union of the types
* for all possible results.
*
* e.g.
* The type:
* `LocatorFnResult<[
* ComponentHarnessConstructor<MyHarness>,
* HarnessPredicate<MyOtherHarness>,
* string
* ]>`
* is equivalent to:
* `MyHarness | MyOtherHarness | TestElement`.
*/
export type LocatorFnResult<T extends (HarnessQuery<any> | string)[]> = {
[I in keyof T]: T[I] extends new (...args: any[]) => infer C // Map `ComponentHarnessConstructor<C>` to `C`.
? C
: // Map `HarnessPredicate<C>` to `C`.
T[I] extends {harnessType: new (...args: any[]) => infer C}
? C
: // Map `string` to `TestElement`.
T[I] extends string
? TestElement
: // Map everything else to `never` (should not happen due to the type constraint on `T`).
never;
}[number];
/**
* Interface used to load ComponentHarness objects. This interface is used by test authors to
* instantiate `ComponentHarness`es.
*/
export interface HarnessLoader {
/**
* Searches for an element with the given selector under the current instances's root element,
* and returns a `HarnessLoader` rooted at the matching element. If multiple elements match the
* selector, the first is used. If no elements match, an error is thrown.
* @param selector The selector for the root element of the new `HarnessLoader`
* @return A `HarnessLoader` rooted at the element matching the given selector.
* @throws If a matching element can't be found.
*/
getChildLoader(selector: string): Promise<HarnessLoader>;
/**
* Searches for all elements with the given selector under the current instances's root element,
* and returns an array of `HarnessLoader`s, one for each matching element, rooted at that
* element.
* @param selector The selector for the root element of the new `HarnessLoader`
* @return A list of `HarnessLoader`s, one for each matching element, rooted at that element.
*/
getAllChildLoaders(selector: string): Promise<HarnessLoader[]>;
/**
* Searches for an instance of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns a `ComponentHarness` for that instance. If multiple
* matching components are found, a harness for the first one is returned. If no matching
* component is found, an error is thrown.
* @param query A query for a harness to create
* @return An instance of the given harness type
* @throws If a matching component instance can't be found.
*/
getHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T>;
/**
* Searches for an instance of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns a `ComponentHarness` for that instance. If multiple
* matching components are found, a harness for the first one is returned. If no matching
* component is found, null is returned.
* @param query A query for a harness to create
* @return An instance of the given harness type (or null if not found).
*/
getHarnessOrNull<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T | null>;
/**
* Searches for an instance of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns a `ComponentHarness` for the instance on the page
* at the given index. If no matching component exists at that index, an error is thrown.
* @param query A query for a harness to create
* @param index The zero-indexed offset of the matching component instance to return
* @return An instance of the given harness type.
* @throws If a matching component instance can't be found at the given index.
*/
getHarnessAtIndex<T extends ComponentHarness>(query: HarnessQuery<T>, index: number): Promise<T>;
/**
* Searches for all instances of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns a list `ComponentHarness` for each instance.
* @param query A query for a harness to create
* @return A list instances of the given harness type.
*/
getAllHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T[]>;
/**
* Searches for all instances of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns the total count of all matching components.
* @param query A query for a harness to create
* @return An integer indicating the number of instances that were found.
*/
countHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<number>;
/**
* Searches for an instance of the component corresponding to the given harness type under the
* `HarnessLoader`'s root element, and returns a boolean indicating if any were found.
* @param query A query for a harness to create
* @return A boolean indicating if an instance was found.
*/
hasHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<boolean>;
}
/**
* Interface used to create asynchronous locator functions used find elements and component
* harnesses. This interface is used by `ComponentHarness` authors to create locator functions for
* their `ComponentHarness` subclass.
*/
export interface LocatorFactory {
/** Gets a locator factory rooted at the document root. */
documentRootLocatorFactory(): LocatorFactory;
/** The root element of this `LocatorFactory` as a `TestElement`. */
rootElement: TestElement;
/**
* Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
* or element under the root element of this `LocatorFactory`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for the
* first element or harness matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If no matches are found, the
* `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
* each query.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'`:
* - `await lf.locatorFor(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
* - `await lf.locatorFor('div', DivHarness)()` gets a `TestElement` instance for `#d1`
* - `await lf.locatorFor('span')()` throws because the `Promise` rejects.
*/
locatorFor<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T>>;
/**
* Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
* or element under the root element of this `LocatorFactory`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for the
* first element or harness matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If no matches are found, the
* `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
* result types for each query or null.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'`:
* - `await lf.locatorForOptional(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
* - `await lf.locatorForOptional('div', DivHarness)()` gets a `TestElement` instance for `#d1`
* - `await lf.locatorForOptional('span')()` gets `null`.
*/
locatorForOptional<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T> | null>;
/**
* Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
* or elements under the root element of this `LocatorFactory`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for all
* elements and harnesses matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If an element matches more than
* one `ComponentHarness` class, the locator gets an instance of each for the same element. If
* an element matches multiple `string` selectors, only one `TestElement` instance is returned
* for that element. The type that the `Promise` resolves to is an array where each element is
* the union of all result types for each query.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'` and `IdIsD1Harness.hostSelector === '#d1'`:
* - `await lf.locatorForAll(DivHarness, 'div')()` gets `[
* DivHarness, // for #d1
* TestElement, // for #d1
* DivHarness, // for #d2
* TestElement // for #d2
* ]`
* - `await lf.locatorForAll('div', '#d1')()` gets `[
* TestElement, // for #d1
* TestElement // for #d2
* ]`
* - `await lf.locatorForAll(DivHarness, IdIsD1Harness)()` gets `[
* DivHarness, // for #d1
* IdIsD1Harness, // for #d1
* DivHarness // for #d2
* ]`
* - `await lf.locatorForAll('span')()` gets `[]`.
*/
locatorForAll<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T>[]>;
/** @return A `HarnessLoader` rooted at the root element of this `LocatorFactory`. */
rootHarnessLoader(): Promise<HarnessLoader>;
/**
* Gets a `HarnessLoader` instance for an element under the root of this `LocatorFactory`.
* @param selector The selector for the root element.
* @return A `HarnessLoader` rooted at the first element matching the given selector.
* @throws If no matching element is found for the given selector.
*/
harnessLoaderFor(selector: string): Promise<HarnessLoader>;
/**
* Gets a `HarnessLoader` instance for an element under the root of this `LocatorFactory`
* @param selector The selector for the root element.
* @return A `HarnessLoader` rooted at the first element matching the given selector, or null if
* no matching element is found.
*/
harnessLoaderForOptional(selector: string): Promise<HarnessLoader | null>;
/**
* Gets a list of `HarnessLoader` instances, one for each matching element.
* @param selector The selector for the root element.
* @return A list of `HarnessLoader`, one rooted at each element matching the given selector.
*/
harnessLoaderForAll(selector: string): Promise<HarnessLoader[]>;
/**
* Flushes change detection and async tasks captured in the Angular zone.
* In most cases it should not be necessary to call this manually. However, there may be some edge
* cases where it is needed to fully flush animation events.
*/
forceStabilize(): Promise<void>;
/**
* Waits for all scheduled or running async tasks to complete. This allows harness
* authors to wait for async tasks outside of the Angular zone.
*/
waitForTasksOutsideAngular(): Promise<void>;
}
/**
* Base class for component harnesses that all component harness authors should extend. This base
* component harness provides the basic ability to locate element and sub-component harness. It
* should be inherited when defining user's own harness.
*/
export abstract class ComponentHarness {
constructor(protected readonly locatorFactory: LocatorFactory) {}
/** Gets a `Promise` for the `TestElement` representing the host element of the component. */
async host(): Promise<TestElement> {
return this.locatorFactory.rootElement;
}
/**
* Gets a `LocatorFactory` for the document root element. This factory can be used to create
* locators for elements that a component creates outside of its own root element. (e.g. by
* appending to document.body).
*/
protected documentRootLocatorFactory(): LocatorFactory {
return this.locatorFactory.documentRootLocatorFactory();
}
/**
* Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
* or element under the host element of this `ComponentHarness`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for the
* first element or harness matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If no matches are found, the
* `Promise` rejects. The type that the `Promise` resolves to is a union of all result types for
* each query.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'`:
* - `await ch.locatorFor(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
* - `await ch.locatorFor('div', DivHarness)()` gets a `TestElement` instance for `#d1`
* - `await ch.locatorFor('span')()` throws because the `Promise` rejects.
*/
protected locatorFor<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T>> {
return this.locatorFactory.locatorFor(...queries);
}
/**
* Creates an asynchronous locator function that can be used to find a `ComponentHarness` instance
* or element under the host element of this `ComponentHarness`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for the
* first element or harness matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If no matches are found, the
* `Promise` is resolved with `null`. The type that the `Promise` resolves to is a union of all
* result types for each query or null.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'`:
* - `await ch.locatorForOptional(DivHarness, 'div')()` gets a `DivHarness` instance for `#d1`
* - `await ch.locatorForOptional('div', DivHarness)()` gets a `TestElement` instance for `#d1`
* - `await ch.locatorForOptional('span')()` gets `null`.
*/
protected locatorForOptional<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T> | null> {
return this.locatorFactory.locatorForOptional(...queries);
}
/**
* Creates an asynchronous locator function that can be used to find `ComponentHarness` instances
* or elements under the host element of this `ComponentHarness`.
* @param queries A list of queries specifying which harnesses and elements to search for:
* - A `string` searches for elements matching the CSS selector specified by the string.
* - A `ComponentHarness` constructor searches for `ComponentHarness` instances matching the
* given class.
* - A `HarnessPredicate` searches for `ComponentHarness` instances matching the given
* predicate.
* @return An asynchronous locator function that searches for and returns a `Promise` for all
* elements and harnesses matching the given search criteria. Matches are ordered first by
* order in the DOM, and second by order in the queries list. If an element matches more than
* one `ComponentHarness` class, the locator gets an instance of each for the same element. If
* an element matches multiple `string` selectors, only one `TestElement` instance is returned
* for that element. The type that the `Promise` resolves to is an array where each element is
* the union of all result types for each query.
*
* e.g. Given the following DOM: `<div id="d1" /><div id="d2" />`, and assuming
* `DivHarness.hostSelector === 'div'` and `IdIsD1Harness.hostSelector === '#d1'`:
* - `await ch.locatorForAll(DivHarness, 'div')()` gets `[
* DivHarness, // for #d1
* TestElement, // for #d1
* DivHarness, // for #d2
* TestElement // for #d2
* ]`
* - `await ch.locatorForAll('div', '#d1')()` gets `[
* TestElement, // for #d1
* TestElement // for #d2
* ]`
* - `await ch.locatorForAll(DivHarness, IdIsD1Harness)()` gets `[
* DivHarness, // for #d1
* IdIsD1Harness, // for #d1
* DivHarness // for #d2
* ]`
* - `await ch.locatorForAll('span')()` gets `[]`.
*/
protected locatorForAll<T extends (HarnessQuery<any> | string)[]>(
...queries: T
): AsyncFactoryFn<LocatorFnResult<T>[]> {
return this.locatorFactory.locatorForAll(...queries);
}
/**
* Flushes change detection and async tasks in the Angular zone.
* In most cases it should not be necessary to call this manually. However, there may be some edge
* cases where it is needed to fully flush animation events.
*/
protected async forceStabilize() {
return this.locatorFactory.forceStabilize();
}
/**
* Waits for all scheduled or running async tasks to complete. This allows harness
* authors to wait for async tasks outside of the Angular zone.
*/
protected async waitForTasksOutsideAngular() {
return this.locatorFactory.waitForTasksOutsideAngular();
}
}
/**
* Base class for component harnesses that authors should extend if they anticipate that consumers
* of the harness may want to access other harnesses within the `<ng-content>` of the component.
*/
export abstract class ContentContainerComponentHarness<S extends string = string>
extends ComponentHarness
implements HarnessLoader
{
async getChildLoader(selector: S): Promise<HarnessLoader> {
return (await this.getRootHarnessLoader()).getChildLoader(selector);
}
async getAllChildLoaders(selector: S): Promise<HarnessLoader[]> {
return (await this.getRootHarnessLoader()).getAllChildLoaders(selector);
}
async getHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T> {
return (await this.getRootHarnessLoader()).getHarness(query);
}
async getHarnessOrNull<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T | null> {
return (await this.getRootHarnessLoader()).getHarnessOrNull(query);
}
async getHarnessAtIndex<T extends ComponentHarness>(
query: HarnessQuery<T>,
index: number,
): Promise<T> {
return (await this.getRootHarnessLoader()).getHarnessAtIndex(query, index);
}
async getAllHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<T[]> {
return (await this.getRootHarnessLoader()).getAllHarnesses(query);
}
async countHarnesses<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<number> {
return (await this.getRootHarnessLoader()).countHarnesses(query);
}
async hasHarness<T extends ComponentHarness>(query: HarnessQuery<T>): Promise<boolean> {
return (await this.getRootHarnessLoader()).hasHarness(query);
}
/**
* Gets the root harness loader from which to start
* searching for content contained by this harness.
*/
protected async getRootHarnessLoader(): Promise<HarnessLoader> {
return this.locatorFactory.rootHarnessLoader();
}
}
/** Constructor for a ComponentHarness subclass. */
export interface ComponentHarnessConstructor<T extends ComponentHarness> {
new (locatorFactory: LocatorFactory): T;
/**
* `ComponentHarness` subclasses must specify a static `hostSelector` property that is used to
* find the host element for the corresponding component. This property should match the selector
* for the Angular component.
*/
hostSelector: string;
}
/** A set of criteria that can be used to filter a list of `ComponentHarness` instances. */
export interface BaseHarnessFilters {
/** Only find instances whose host element matches the given selector. */
selector?: string;
/** Only find instances that are nested under an element with the given selector. */
ancestor?: string;
}
/**
* A class used to associate a ComponentHarness class with predicates functions that can be used to
* filter instances of the class.
*/
export class HarnessPredicate<T extends ComponentHarness> {
private _predicates: AsyncPredicate<T>[] = [];
private _descriptions: string[] = [];
private _ancestor: string;
constructor(
public harnessType: ComponentHarnessConstructor<T>,
options: BaseHarnessFilters,
) {
this._addBaseOptions(options);
}
/**
* Checks if the specified nullable string value matches the given pattern.
* @param value The nullable string value to check, or a Promise resolving to the
* nullable string value.
* @param pattern The pattern the value is expected to match. If `pattern` is a string,
* `value` is expected to match exactly. If `pattern` is a regex, a partial match is
* allowed. If `pattern` is `null`, the value is expected to be `null`.
* @return Whether the value matches the pattern.
*/
static async stringMatches(
value: string | null | Promise<string | null>,
pattern: string | RegExp | null,
): Promise<boolean> {
value = await value;
if (pattern === null) {
return value === null;
} else if (value === null) {
return false;
}
return typeof pattern === 'string' ? value === pattern : pattern.test(value);
}
/**
* Adds a predicate function to be run against candidate harnesses.
* @param description A description of this predicate that may be used in error messages.
* @param predicate An async predicate function.
* @return this (for method chaining).
*/
add(description: string, predicate: AsyncPredicate<T>) {
this._descriptions.push(description);
this._predicates.push(predicate);
return this;
}
/**
* Adds a predicate function that depends on an option value to be run against candidate
* harnesses. If the option value is undefined, the predicate will be ignored.
* @param name The name of the option (may be used in error messages).
* @param option The option value.
* @param predicate The predicate function to run if the option value is not undefined.
* @return this (for method chaining).
*/
addOption<O>(name: string, option: O | undefined, predicate: AsyncOptionPredicate<T, O>) {
if (option !== undefined) {
this.add(`${name} = ${_valueAsString(option)}`, item => predicate(item, option));
}
return this;
}
/**
* Filters a list of harnesses on this predicate.
* @param harnesses The list of harnesses to filter.
* @return A list of harnesses that satisfy this predicate.
*/
async filter(harnesses: T[]): Promise<T[]> {
if (harnesses.length === 0) {
return [];
}
const results = await parallel(() => harnesses.map(h => this.evaluate(h)));
return harnesses.filter((_, i) => results[i]);
}
/**
* Evaluates whether the given harness satisfies this predicate.
* @param harness The harness to check
* @return A promise that resolves to true if the harness satisfies this predicate,
* and resolves to false otherwise.
*/
async evaluate(harness: T): Promise<boolean> {
const results = await parallel(() => this._predicates.map(p => p(harness)));
return results.reduce((combined, current) => combined && current, true);
}
/** Gets a description of this predicate for use in error messages. */
getDescription() {
return this._descriptions.join(', ');
}
/** Gets the selector used to find candidate elements. */
getSelector() {
// We don't have to go through the extra trouble if there are no ancestors.
if (!this._ancestor) {
return (this.harnessType.hostSelector || '').trim();
}
const [ancestors, ancestorPlaceholders] = _splitAndEscapeSelector(this._ancestor);
const [selectors, selectorPlaceholders] = _splitAndEscapeSelector(
this.harnessType.hostSelector || '',
);
const result: string[] = [];
// We have to add the ancestor to each part of the host compound selector, otherwise we can get
// incorrect results. E.g. `.ancestor .a, .ancestor .b` vs `.ancestor .a, .b`.
ancestors.forEach(escapedAncestor => {
const ancestor = _restoreSelector(escapedAncestor, ancestorPlaceholders);
return selectors.forEach(escapedSelector =>
result.push(`${ancestor} ${_restoreSelector(escapedSelector, selectorPlaceholders)}`),
);
});
return result.join(', ');
}
/** Adds base options common to all harness types. */
private _addBaseOptions(options: BaseHarnessFilters) {
this._ancestor = options.ancestor || '';
if (this._ancestor) {
this._descriptions.push(`has ancestor matching selector "${this._ancestor}"`);
}
const selector = options.selector;
if (selector !== undefined) {
this.add(`host matches selector "${selector}"`, async item => {
return (await item.host()).matchesSelector(selector);
});
}
}
}
/** Represent a value as a string for the purpose of logging. */
function _valueAsString(value: unknown) {
if (value === undefined) {
return 'undefined';
}
try {
// `JSON.stringify` doesn't handle RegExp properly, so we need a custom replacer.
// Use a character that is unlikely to appear in real strings to denote the start and end of
// the regex. This allows us to strip out the extra quotes around the value added by
// `JSON.stringify`. Also do custom escaping on `"` characters to prevent `JSON.stringify`
// from escaping them as if they were part of a string.
const stringifiedValue = JSON.stringify(value, (_, v) =>
v instanceof RegExp
? `◬MAT_RE_ESCAPE◬${v.toString().replace(/"/g, '◬MAT_RE_ESCAPE◬')}◬MAT_RE_ESCAPE◬`
: v,
);
// Strip out the extra quotes around regexes and put back the manually escaped `"` characters.
return stringifiedValue
.replace(/"◬MAT_RE_ESCAPE◬|◬MAT_RE_ESCAPE◬"/g, '')
.replace(/◬MAT_RE_ESCAPE◬/g, '"');
} catch {
// `JSON.stringify` will throw if the object is cyclical,
// in this case the best we can do is report the value as `{...}`.
return '{...}';
}
}
/**
* Splits up a compound selector into its parts and escapes any quoted content. The quoted content
* has to be escaped, because it can contain commas which will throw throw us off when trying to
* split it.
* @param selector Selector to be split.
* @returns The escaped string where any quoted content is replaced with a placeholder. E.g.
* `[foo="bar"]` turns into `[foo=__cdkPlaceholder-0__]`. Use `_restoreSelector` to restore
* the placeholders.
*/
function _splitAndEscapeSelector(selector: string): [parts: string[], placeholders: string[]] {
const placeholders: string[] = [];
// Note that the regex doesn't account for nested quotes so something like `"ab'cd'e"` will be
// considered as two blocks. It's a bit of an edge case, but if we find that it's a problem,
// we can make it a bit smarter using a loop. Use this for now since it's more readable and
// compact. More complete implementation:
// https://github.com/angular/angular/blob/bd34bc9e89f18a/packages/compiler/src/shadow_css.ts#L655
const result = selector.replace(/(["'][^["']*["'])/g, (_, keep) => {
const replaceBy = `__cdkPlaceholder-${placeholders.length}__`;
placeholders.push(keep);
return replaceBy;
});
return [result.split(',').map(part => part.trim()), placeholders];
}
/** Restores a selector whose content was escaped in `_splitAndEscapeSelector`. */
function _restoreSelector(selector: string, placeholders: string[]): string {
return selector.replace(/__cdkPlaceholder-(\d+)__/g, (_, index) => placeholders[+index]);
}