Testing
Your first harness test
The harnesses are in the @vigdx/ui/testing entry point, built on the Angular CDK's @angular/cdk/testing, which your app already has as a peer dependency. Load them from a TestBed fixture and filter with with(…), as with Angular Material's harnesses:
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { ButtonHarness, InputFieldHarness } from '@vigdx/ui/testing';
import { Newsletter } from './newsletter';
it('subscribes with an email address', async () => {
TestBed.configureTestingModule({ providers: [provideZonelessChangeDetection()] });
const fixture = TestBed.createComponent(Newsletter);
const loader = TestbedHarnessEnvironment.loader(fixture);
const email = await loader.getHarness(InputFieldHarness.with({ label: 'Email' }));
const subscribe = await loader.getHarness(ButtonHarness.with({ text: 'Subscribe' }));
expect(await subscribe.isDisabled()).toBe(true);
await email.setValue('[email protected]');
expect(await subscribe.isDisabled()).toBe(false);
await subscribe.click();
}); Every method is asynchronous and runs change detection before it reads or after it acts, so a test needs no fixture.detectChanges() or whenStable() of its own. Text fields type key by key, as a user does; NumberInputHarness.setValue() takes the text in the field's locale ('1.234,5' in German) and commits it by blurring the field, so it never presses Enter in a form. The package root @vigdx/ui does not re-export the testing entry point: test code never reaches an app bundle.
Overlays
Select-type panels, menus, popovers and tooltips render in the CDK overlay container at the end of <body>. Their harnesses follow the trigger to its own panel: the aria-controls of a combobox, menu or popover trigger, and the data-tooltip-trigger of a tooltip trigger, which holds the id of its bubble. A loader from the fixture therefore finds the options, items and content. Dialogs opened by the Dialogs service are appended to <body> too; load those from TestbedHarnessEnvironment.documentRootLoader(fixture).
// A select's options render in the CDK overlay container, outside the
// fixture: the harness opens the panel and finds them there.
const country = await loader.getHarness(SelectHarness.with({ label: 'Country' }));
await country.selectOption({ text: 'Germany' });
expect(await country.getValueText()).toBe('Germany');
// Menus: click down a path of submenus.
const actions = await loader.getHarness(MenuHarness.with({ triggerText: 'Actions' }));
await actions.clickItem({ text: 'Export' }, { text: 'PDF' });
// Dialogs the Dialogs service opens are appended to <body>: load them from
// the document root.
const root = TestbedHarnessEnvironment.documentRootLoader(fixture);
const dialog = await root.getHarness(DialogHarness.with({ heading: 'Rename' }));
const name = await dialog.getHarness(InputFieldHarness.with({ label: 'Name' }));
await name.setValue('Q3 report');
await (await dialog.getHarness(ButtonHarness.with({ text: 'Save' }))).click(); As with Angular Material's harnesses, methods that read a popup (getOptions(), getItems(), getPeriodLabel(), getPanelText()…) need it open and throw a message saying so; call open() first. Actions (selectOption(), clickItem(), selectDay()…) open it themselves.
Actions that open or close an overlay wait for its entry and exit transitions: the kit marks the animating element with data-opening or data-closing, stable hooks listed with each component's parts, and the harness returns once the overlay it acted on (or the element it clicked inside one) carries neither. It throws when they are still there after three seconds; the kit caps its transitions at two. In jsdom nothing animates, so this costs nothing; in a real browser a closed dialog or menu is gone when close() resolves, and a test cannot catch it halfway.
Note
setTimeout, Date.now()) and return at once when nothing animates, which in jsdom is always. In a browser test that installs fake timers (vi.useFakeTimers(), fakeAsync), advance or flush the timers yourself while an overlay animates: the CDK's stabilization does not drive them. Unit tests in jsdom
The kit runs zoneless, with OnPush components on signals. Its own suite uses provideZonelessChangeDetection() with Vitest and jsdom, plus two stand-ins for browser APIs jsdom lacks:
beforeEach(() => {
// jsdom implements neither modal <dialog> nor scrollIntoView. Minimal
// stand-ins let vig-dialog, vig-drawer and vig-confirm-dialog open and
// list panels scroll; ??= keeps a real implementation where one exists.
HTMLDialogElement.prototype.showModal ??= function (this: HTMLDialogElement) {
this.setAttribute('open', '');
};
HTMLDialogElement.prototype.close ??= function (this: HTMLDialogElement) {
this.removeAttribute('open');
this.dispatchEvent(new Event('close'));
};
Element.prototype.scrollIntoView ??= () => {};
});
// Overlays live in the container; reset it between tests.
afterEach(() => TestBed.inject(OverlayContainer).ngOnDestroy());Note
0 in every TestBed test (see Element ids). Harnesses find elements by label, text and state, never by id. Forms
A harness drives the control, not the form API, so the same test works with Signal Forms and with Reactive Forms through VigValueAccessor. Typing (setValue) dispatches key and input events; blur() marks the field touched, which shows its error by default.
// Reactive Forms (through VigValueAccessor) and Signal Forms ([formField])
// look the same to a harness: it drives the control as a user does.
const email = await loader.getHarness(InputFieldHarness.with({ label: 'Email' }));
await email.setValue('not-an-email');
await email.blur(); // touched: the error shows
expect(await email.isInvalid()).toBe(true);
expect(await email.getErrorMessage()).toBe('Enter a valid email');
await (await loader.getHarness(RadioGroupHarness.with({ label: 'Plan' }))).checkRadioButton({
label: 'Pro',
});
await (await loader.getHarness(CheckboxHarness.with({ label: 'Accept terms' }))).check();
expect(component.form.valid).toBe(true);Tables and trees
TableHarness reads rendered rows: the current page, and with virtualScroll the rows in the window, plus a focused row the table keeps rendered while it is scrolled away. Rows, headers and controls of tables nested in expansion rows belong to those tables, not to the outer one (accordions nested in an item likewise). Rows match by cell text, selection and expanded state; header cells sort. TreeHarness.expandPath('Archive', 'src') looks for each label among the children of the previous one and waits while lazy children load.
const table = await loader.getHarness(TableHarness);
await table.sortBy('Age');
expect((await table.getCellTextByColumnName())['Age']).toEqual(['29', '36', '41']);
const [grace] = await table.getRows({ cellText: 'Grace' });
await grace.selectRow();
await grace.expand(); // a tree row, or a row with an expansion template
await (await table.getPaginator())?.goToNextPage();Available harnesses
| Component | Harness | Key methods |
|---|---|---|
vig-button | ButtonHarness | click, getText, isDisabled, isLoading |
vig-input, vig-password, vig-number-input, vig-input-mask, vig-input-otp | InputFieldHarness, PasswordHarness, NumberInputHarness, InputMaskHarness, InputOtpHarness | getValue, setValue, getLabel, getErrorMessage, isInvalid, toggleMask, increment |
vig-chip, vig-tag | ChipHarness | getLabel, isRemovable, remove |
vig-checkbox, vig-toggle-switch | CheckboxHarness, ToggleSwitchHarness | isChecked, check, uncheck, toggle, isIndeterminate |
vig-radio-group | RadioGroupHarness, RadioButtonHarness | getRadioButtons, checkRadioButton, getCheckedLabel |
vig-select, vig-multi-select, vig-autocomplete | SelectHarness, MultiSelectHarness, AutocompleteHarness, OptionHarness | open, close, getOptions, selectOption, selectOptions, setFilterText, enterText, clear |
vig-date-picker | DatePickerHarness | setValue, openCalendar, selectDay, selectDate, goToNextPeriod, getPeriodLabel |
vig-listbox, vig-slider, vig-rating | ListboxHarness, SliderHarness, RatingHarness | getOptions, clickOptions, getValue, setValue, rate |
vig-dialog (also Dialogs), vig-drawer, vig-confirm-dialog | DialogHarness, DrawerHarness, ConfirmDialogHarness | isOpen, getHeading, close, cancel, accept, reject, getHarness(…) |
vig-menu, vig-menubar | MenuHarness, MenuItemHarness, MenubarHarness | open, getItems, clickItem(…path), getSubmenu, isChecked |
vig-toaster, vigTooltip, vig-popover | ToasterHarness, ToastHarness, TooltipHarness, PopoverHarness | getToasts, getMessage, close, show, hide, getTooltipText |
vig-tabs, vig-accordion, vig-stepper | TabsHarness, TabHarness, AccordionHarness, AccordionItemHarness, StepperHarness | selectTab, getHarnessLoaderForContent, expand, collapse, selectStep |
vig-table, vig-paginator | TableHarness, TableRowHarness, TableCellHarness, TableHeaderCellHarness, PaginatorHarness | getRows, getCellTextByColumnName, sortBy, selectRow, toggleSelectAll, expand, goToPage |
vig-tree, vig-tree-select | TreeHarness, TreeNodeHarness, TreeSelectHarness | getNodes, expandPath, expand, click, selectNode, getTree |
Field harnesses share FormFieldControlHarness: getLabel, getHint, getErrorMessage, isDisabled, isRequired, isReadonly, isInvalid, focus and blur. Their with() filters take label and disabled; the text fields also placeholder and value.
Harnesses for your components
Compose the kit's harnesses into harnesses of your own screens. The kit's harnesses find elements through its public hooks only: data-scope / data-part, literal data-state values and the other data-* attributes the API report records for each component (a removal fails the semver gate), plus the WAI-ARIA roles and states the components implement. A refactor of a component's markup does not break your tests; do the same with your own selectors.
import { ComponentHarness } from '@angular/cdk/testing';
import { ButtonHarness } from '@vigdx/ui/testing';
export class CheckoutHarness extends ComponentHarness {
static hostSelector = 'app-checkout';
private readonly pay = this.locatorFor(ButtonHarness.with({ text: 'Pay now' }));
private readonly total = this.locatorFor('[data-testid="total"]');
async getTotal(): Promise<string> {
return (await this.total()).text();
}
async payNow(): Promise<void> {
return (await this.pay()).click();
}
}End-to-end tests
Harnesses talk to the page only through the CDK's TestElement interface, so the same harness runs in any harness environment. The CDK ships two: TestbedHarnessEnvironment (@angular/cdk/testing/testbed) for unit tests and SeleniumWebDriverHarnessEnvironment (@angular/cdk/testing/selenium-webdriver) for Selenium WebDriver. Its Protractor environment was removed along with Protractor. Playwright and Cypress have no environment in the CDK: use a community package or extend the CDK's HarnessEnvironment yourself.
In a real browser, DialogHarness.cancel() fires the dialog's native cancel event, which is what Escape does; to test the key itself, press it with your end-to-end tool.