javascript / expert
Snippet
Decoupled Integration Testing with Component Harnesses
Component Harnesses provide an abstraction layer for testing, allowing you to interact with components via a stable API rather than querying the DOM directly. This makes tests resilient to changes in internal HTML structure or third-party library updates.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';import { MatButtonHarness } from '@angular/material/button/testing';it('should click the submit button', async () => {const fixture = TestBed.createComponent(MyComponent);const loader = TestbedHarnessEnvironment.loader(fixture);const button = await loader.getHarness(MatButtonHarness);await button.click();expect(fixture.componentInstance.submitted).toBe(true);});
angular
Breakdown
1
TestbedHarnessEnvironment.loader(fixture)
Creates a HarnessLoader instance associated with the current test fixture.
2
loader.getHarness(MatButtonHarness)
Asynchronously locates the harness for a specific component (e.g., an Angular Material button).
3
await button.click()
Interacts with the component using the harness's high-level API, abstracting away the DOM event logic.