`@angular/cdk/testing` provides infrastructure to help with testing Angular components. ### Component test harnesses A component harness is a class that lets a test interact with a component via a supported API. Each harness's API interacts with a component the same way a user would. By using the harness API, a test insulates itself against updates to the internals of a component, such as changing its DOM structure. The idea for component harnesses comes from the [PageObject](https://martinfowler.com/bliki/PageObject.html) pattern commonly used for integration testing. `@angular/cdk/testing` contains infrastructure for creating and using component test harnesses. You can create test harnesses for any component, ranging from small reusable widgets to full application pages. The component harness system supports multiple testing environments. You can use the same harness implementation in both unit and end-to-end tests. This means that users only need to learn one API, and component authors don't have to maintain separate unit and end-to-end test implementations. Common component libraries, in particular, benefit from this infrastructure due to the wide use of their components. Providing a test harness allows the consumers of a component to write tests that avoid dependencies on any private implementation details. By capturing these implementation details in a single place, consumers can more easily update to new library versions. This document provides guidance for three types of developers: 1. [Test authors](#api-for-test-authors) 2. [Component harness authors](#api-for-component-harness-authors) 3. [Harness environment authors](#api-for-harness-environment-authors) Since many developers fall into only one of these categories, the relevant APIs are broken out by developer type in the sections below. ### API for test authors Test authors are developers using component harnesses written by someone else to test their application. For example, this could be an app developer who uses a third-party menu component and needs to interact with the menu in a unit test. #### Working with `ComponentHarness` classes `ComponentHarness` is the abstract base class for all component harnesses. Every harness extends this class. All `ComponentHarness` subclasses have a static property, `hostSelector`, that matches the harness class to instances of the component in the DOM. Beyond that, the API of any given harness is specific to its corresponding component; refer to the component's documentation to learn how to use a specific harness. #### Using `TestbedHarnessEnvironment` and `SeleniumWebDriverHarnessEnvironment` These classes correspond to different implementations of the component harness system with bindings for specific test environments. Any given test must only import _one_ of these classes. Karma-based unit tests should use the `TestbedHarnessEnvironment`, while Selenium WebDriver-based end-to-end tests should use the `SeleniumWebDriverHarnessEnvironment`. Additional environments require custom bindings; see [API for harness environment authors](#api-for-harness-environment-authors) for more information on alternate test environments. These classes are primarily used to create a `HarnessLoader` instance, and in certain cases, to create `ComponentHarness` instances directly. `TestbedHarnessEnvironment` offers the following static methods: | Method | Description | | ------ | ----------- | | `loader(fixture: ComponentFixture): HarnessLoader` | Gets a `HarnessLoader` instance for the given fixture, rooted at the fixture's root element. Should be used to create harnesses for elements contained inside the fixture | | `documentRootLoader(fixture: ComponentFixture): HarnessLoader` | Gets a `HarnessLoader` instance for the given fixture, rooted at the HTML document's root element. Can be used to create harnesses for elements that fall outside of the fixture | | `harnessForFixture(fixture: ComponentFixture, harnessType: ComponentHarnessConstructor): Promise` | Used to create a `ComponentHarness` instance for the fixture's root element directly. This is necessary when bootstrapping the test with the component you plan to load a harness for, because Angular does not set the proper tag name when creating the fixture. | In most cases, you can create a `HarnessLoader` in the `beforeEach` block using `TestbedHarnessEnvironment.loader(fixture)` and then use that `HarnessLoader` to create any necessary `ComponentHarness` instances. The other methods cover special cases as shown in this example: Consider a reusable dialog-button component that opens a dialog on click, containing the following components, each with a corresponding harness: - `MyDialogButton` (composes the `MyButton` and `MyDialog` with a convenient API) - `MyButton` (a simple button component) - `MyDialog` (a dialog appended to `document.body` by `MyDialogButton` upon click) The following code loads harnesses for each of these components: ```ts let fixture: ComponentFixture; let loader: HarnessLoader; let rootLoader: HarnessLoader; beforeEach(() => { fixture = TestBed.createComponent(MyDialogButton); loader = TestbedHarnessEnvironment.loader(fixture); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); it('loads harnesses', async () => { // Load a harness for the bootstrapped component with `harnessForFixture` dialogButtonHarness = await TestbedHarnessEnvironment.harnessForFixture(fixture, MyDialogButtonHarness); // The button element is inside the fixture's root element, so we use `loader`. const buttonHarness = await loader.getHarness(MyButtonHarness); // Click the button to open the dialog await buttonHarness.click(); // The dialog is appended to `document.body`, outside of the fixture's root element, // so we use `rootLoader` in this case. const dialogHarness = await rootLoader.getHarness(MyDialogHarness); // ... make some assertions }); ``` `SeleniumWebDriverHarnessEnvironment` has an API that offers a single static method: | Method | Description | | ------ | ----------- | | `loader(): HarnessLoader` | Gets a `HarnessLoader` instance for the current HTML document, rooted at the document's root element. | Since Selenium WebDriver does not deal with fixtures, the API in this environment is simpler. The `HarnessLoader` returned by the `loader()` method should be sufficient for loading all necessary `ComponentHarness` instances. Please note that harnesses may not behave _exactly_ the same in all environments. There will always be some difference between the real browser-generated event sequence when a user clicks or types in an element, versus the simulated event sequence generated in unit tests. Instead, the CDK makes a best effort to normalize the behavior and simulate the most important events in the sequence. #### Creating harnesses with `HarnessLoader` Instances of this class correspond to a specific DOM element (the "root element" of the loader) and are used to create `ComponentHarness` instances for elements under this root element. `HarnessLoader` instances have the following methods: | Method | Description | | ------ | ----------- | | `getChildLoader(selector: string): Promise` | Searches for an element matching the given selector below the root element of this `HarnessLoader`, and returns a new `HarnessLoader` rooted at the first matching element | | `getAllChildLoaders(selector: string): Promise` | Acts like `getChildLoader`, but returns an array of `HarnessLoader` instances, one for each matching element, rather than just the first matching element | | `getHarness(harnessType: ComponentHarnessConstructor \| HarnessPredicate): Promise` | Searches for an instance of the given `ComponentHarness` class or `HarnessPredicate` below the root element of this `HarnessLoader` and returns an instance of the harness corresponding to the first matching element | | `getHarnessAtIndex(harnessType: ComponentHarnessConstructor \| HarnessPredicate, index: number): Promise` | Acts like `getHarness`, but returns an instance of the harness corresponding to the matching element with the given index (zero-indexed) | | `getAllHarnesses(harnessType: ComponentHarnessConstructor \| HarnessPredicate): Promise` | Acts like `getHarness`, but returns an array of harness instances, one for each matching element, rather than just the first matching element | | `countHarnesses(harnessType: ComponentHarnessConstructor \| HarnessPredicate): Promise` | Counts the number of instances of the given `ComponentHarness` class or `HarnessPredicate` below the root element of this `HarnessLoader`, and returns the result. | | `hasHarness(harnessType: ComponentHarnessConstructor \| HarnessPredicate): Promise` | Returns true if an instance of the given `ComponentHarness` class or `HarnessPredicate` exists below the root element of this `HarnessLoader` | Calls to the harness functions can either take `ComponentHarness` subclass or a `HarnessPredicate`. `HarnessPredicate` applies additional restrictions to the search (e.g. searching for a button that has some particular text, etc). The [details of `HarnessPredicate`](#filtering-harness-instances-with-harnesspredicate) are discussed in the [API for component harness authors](#api-for-component-harness-authors); harness authors should provide convenience methods on their `ComponentHarness` subclass to facilitate the creation of `HarnessPredicate` instances. However, if the harness author's API is not sufficient, they can be created manually. #### Change detection By default, test harnesses will run Angular's change detection before reading the state of a DOM element and after interacting with a DOM element. While convenient in most cases, there may be times that you need finer-grained control over change detection. For example, you may want to check the state of a component while an async operation is pending. In these cases you can use the `manualChangeDetection` function to disable automatic handling of change detection for a block of code. For example: ```ts it('checks state while async action is in progress', async () => { const buttonHarness = loader.getHarness(MyButtonHarness); await manualChangeDetection(async () => { await buttonHarness.click(); fixture.detectChanges(); // Check expectations while async click operation is in progress. expect(isProgressSpinnerVisible()).toBe(true); await fixture.whenStable(); // Check expectations after async click operation complete. expect(isProgressSpinnerVisible()).toBe(false); }); }); ``` #### Working with asynchronous component harness methods To support both unit and end-to-end tests, and to insulate tests against changes in asynchronous behavior, almost all harness methods are asynchronous and return a `Promise`; therefore, the Angular team recommends using [ES2017 `async`/`await` syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) to improve the test readability. Note that `await` statements block the execution of your test until the associated `Promise` resolves. Occasionally, you may want to perform multiple actions simultaneously and wait until they're all done rather than performing each action sequentially. For example, reading multiple properties off a single component. In these situations use the `parallel` function to parallelize the operations. The parallel function works similarly to `Promise.all`, while also optimizing change detection, so it is not run an excessive number of times. The following code demonstrates how you can read multiple properties from a harness with `parallel`: ```ts it('reads properties in parallel', async () => { const checkboxHarness = loader.getHarness(MyCheckboxHarness); // Read the checked and intermediate properties simultaneously. const [checked, indeterminate] = await parallel(() => [ checkboxHarness.isChecked(), checkboxHarness.isIndeterminate() ]); expect(checked).toBe(false); expect(indeterminate).toBe(true); }); ``` ### API for component harness authors Component harness authors are developers who maintain some reusable Angular component, and want to create a test harness for it, that users of the component can use in their tests. For example, this could be an author of a third party Angular component library or a developer who maintains a set of common components for a large Angular application. #### Extending `ComponentHarness` The abstract `ComponentHarness` class is the base class for all component harnesses. To create a custom component harness, extend `ComponentHarness` and implement the static property `hostSelector`. The `hostSelector` property identifies elements in the DOM that match this harness subclass. In most cases, the `hostSelector` should be the same as the `selector` of the corresponding `Component` or `Directive`. For example, consider a simple popup component: ```ts @Component({ selector: 'my-popup', template: `
` }) class MyPopup { @Input() triggerText: string; open = false; toggle() { this.open = !this.open; } } ``` In this case, a minimal harness for the component would look like the following: ```ts class MyPopupHarness extends ComponentHarness { static hostSelector = 'my-popup'; } ``` While `ComponentHarness` subclasses require only the `hostSelector` property, most harnesses should also implement a static `with` method to generate `HarnessPredicate` instances. The [`HarnessPredicate`](#filtering-harness-instances-with-harnesspredicate) section below covers this in more detail. #### Finding elements in the component's DOM Each instance of a `ComponentHarness` subclass represents a particular instance of the corresponding component. You can access the component's host element via the `host` method from the `ComponentHarness` base class. `ComponentHarness` additionally offers several methods for locating elements within the component's DOM. These methods are `locatorFor`, `locatorForOptional`, and `locatorForAll`. Note, though, that these methods do not directly find elements. Instead, they _create functions_ that find elements. This approach safeguards against caching references to out-of-date elements. For example, when an `ngIf` hides and then shows an element, the result is a new DOM element; using functions ensures that tests always reference the current state of the DOM. | Method | Description | | ------ | ----------- | | `host(): Promise` | Returns a `Promise` for the host element of the corresponding component instance. | | `locatorFor(selector: string): () => Promise` | Creates a function that returns a `Promise` for the first element matching the given selector when called. If no matching element is found, the `Promise` rejects. | | `locatorForOptional(selector: string): () => Promise` | Creates a function that returns a `Promise` for the first element matching the given selector when called. If no matching element is found, the `Promise` is resolved with `null`. | | `locatorForAll(selector: string): () => Promise` | Creates a function that returns a `Promise` for a list of all elements matching the given selector when called. | For example, the `MyPopupHarness` class discussed above could provide methods to get the trigger and content elements as follows: ```ts class MyPopupHarness extends ComponentHarness { static hostSelector = 'my-popup'; /** Gets the trigger element */ getTriggerElement = this.locatorFor('button'); /** Gets the content element. */ getContentElement = this.locatorForOptional('.my-popup-content'); } ``` #### Working with `TestElement` instances The functions created with the locator methods described above all return `TestElement` instances. `TestElement` offers a number of methods to interact with the underlying DOM: | Method | Description | | ------ | ----------- | | `blur(): Promise` | Blurs the element. | | `clear(): Promise` | Clears the text in the element (intended for `` and `