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