@angular/cdk/testing package provides utilities for creating component test harnesses that interact with components in tests.
Installation
Creating a Test Harness
Basic Harness
Using the Harness
Advanced Harnesses
Form Harness
Nested Harnesses
Harness Loaders
Document Root Loader
Child Harness Loader
API Reference
ComponentHarness
Base Methods:| Method | Returns | Description |
|---|---|---|
host() | Promise<TestElement> | Get host element |
locatorFor(selector) | AsyncFactoryFn<TestElement> | Locate single element |
locatorForOptional(selector) | AsyncFactoryFn<TestElement | null> | Locate optional element |
locatorForAll(selector) | AsyncFactoryFn<TestElement[]> | Locate all elements |
TestElement
| Method | Returns | Description |
|---|---|---|
click() | Promise<void> | Click element |
sendKeys(...keys) | Promise<void> | Send keyboard input |
clear() | Promise<void> | Clear input value |
text() | Promise<string> | Get text content |
getAttribute(name) | Promise<string | null> | Get attribute |
hasClass(name) | Promise<boolean> | Check if has class |
getDimensions() | Promise<ElementDimensions> | Get element size |
getProperty<T>(name) | Promise<T> | Get property value |
blur() | Promise<void> | Blur element |
focus() | Promise<void> | Focus element |
isFocused() | Promise<boolean> | Check if focused |
Best Practices
- Use harnesses over direct DOM access - More maintainable and reliable
- Create reusable harnesses - Share harnesses across tests
- Test user interactions - Click, type, navigate like a real user
- Avoid implementation details - Test public API, not internals
- Async/await - All harness methods are asynchronous