javascript / intermediate
Snippet
Component Unit Testing with Angular Component Harnesses
Angular CDK Component Harnesses provide an abstraction layer over component internals for testing. Instead of querying raw DOM elements via CSS selectors that break on markup changes, harnesses offer an official, strongly typed API that mimics user interactions and insulates tests from structural DOM refactoring.
snippet.js
javascript
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
import { ComponentFixture, TestBed } from '@angular/core/testing';import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';import { MatButtonHarness } from '@angular/material/button/testing';import { SubmitButtonComponent } from './submit-button.component';describe('SubmitButtonComponent', () => {let fixture: ComponentFixture<SubmitButtonComponent>;beforeEach(async () => {await TestBed.configureTestingModule({imports: [SubmitButtonComponent]}).compileComponents();fixture = TestBed.createComponent(SubmitButtonComponent);});it('should disable submit button when processing', async () => {const loader = TestbedHarnessEnvironment.loader(fixture);const buttonHarness = await loader.getHarness(MatButtonHarness.with({ text: 'Submit' }));fixture.componentInstance.isProcessing.set(true);const isDisabled = await buttonHarness.isDisabled();expect(isDisabled).toBe(true);});});
angular
Breakdown
1
const loader = TestbedHarnessEnvironment.loader(fixture);
Initializes the harness loader tied to the active Testbed component fixture environment.
2
const buttonHarness = await loader.getHarness(MatButtonHarness.with({ text: 'Submit' }));
Locates the Material button harness matching specific criteria such as button label text.
3
const isDisabled = await buttonHarness.isDisabled();
Asynchronously queries the button's disabled state through the harness API without direct DOM inspection.