0 day streak
javascript / expert
Snippet

Building Custom ComponentHarness Abstractions for Isolated UI Testing

Implementation of an Angular Component Test Harness utilizing ComponentHarness and HarnessPredicate from @angular/cdk/testing to create resilient page object abstractions for integration tests.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ComponentHarness, HarnessPredicate } from '@angular/cdk/testing';
export class CustomButtonHarness extends ComponentHarness {
static hostSelector = 'app-custom-button';
static with(options: { text?: string }): HarnessPredicate<CustomButtonHarness> {
return new HarnessPredicate(CustomButtonHarness, options)
.addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text)
);
}
async getText(): Promise<string> {
const host = await this.host();
return host.text();
}
}
angular
Breakdown
1
export class CustomButtonHarness extends ComponentHarness
Extends the base CDK ComponentHarness to encapsulate UI element query logic for component tests.
2
static hostSelector = 'app-custom-button';
Defines the CSS selector used by the harness framework to locate instances of this component in DOM.
3
static with(options: { text?: string }): HarnessPredicate<CustomButtonHarness>
Configures dynamic query predicates allowing tests to filter component instances by properties like text content.
4
const host = await this.host();
Asynchronously acquires the TestElement wrapper representing the host DOM node.