Sub topic 6
Querying the DOM and triggering events
This chapter assumes you have read the chapters on TestBed and fixtures. You should be able to create a component with TestBed.createComponent, call fixture.detectChanges(), and write describe, it, and expect blocks. Here you learn how to find elements in the rendered output, how to act on them like a user would, and which mistakes make these tests pass for the wrong reason.
What a component test sees
After detectChanges() renders the template, the component exists as real DOM nodes. A test has two views of those nodes:
fixture.nativeElementis the host element. It is a plain DOMHTMLElement, so all browser APIs work on it (querySelector,click(),dispatchEvent()).fixture.debugElementis an Angular wrapper around the same tree. It addsquery,queryAll, andtriggerEventHandler, and it knows about directives and listeners.
Most tests only need nativeElement. Reach for debugElement when you need an Angular-specific feature.
The component under test
The examples use a small form. It disables its button until the name is non-empty, and it shows a confirmation after saving.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-name-form',
template: `
<label for="name">Name</label>
<input id="name" type="text" [value]="name()" (input)="onInput($event)" />
<button type="button" [disabled]="!valid()" (click)="submit()">Save</button>
@if (saved()) {
<p data-testid="saved">Saved {{ name() }}</p>
}
`,
})
export class NameFormComponent {
protected readonly name = signal('');
protected readonly saved = signal(false);
protected readonly valid = computed(() => this.name().trim().length > 0);
protected onInput(event: Event) {
this.name.set((event.target as HTMLInputElement).value);
this.saved.set(false);
}
protected submit() {
this.saved.set(true);
}
}Querying with the DOM API
querySelector returns the first match or null. querySelectorAll returns a static NodeList. Pass a type argument so TypeScript knows which element you get back.
const root: HTMLElement = fixture.nativeElement;
const input = root.querySelector<HTMLInputElement>('input');
const items = root.querySelectorAll<HTMLLIElement>('li');Because the result can be null, you have two choices. A non-null assertion (!) makes a missing element throw a TypeError as soon as you use it. A helper that throws a clear message gives a better failure:
function query<T extends Element>(root: HTMLElement, selector: string): T {
const el = root.querySelector<T>(selector);
if (!el) {
throw new Error(`No element matches "${selector}"`);
}
return el;
}Choosing selectors
A selector decides how often the test breaks when the template changes.
| Selector | Example | Breaks when |
|---|---|---|
| Tag | `button` | A second button is added |
| CSS class | `.save-btn` | Styling is renamed |
| Test attribute | `[data-testid="saved"]` | The attribute is removed |
| Role or label | `button[type="button"]` | The semantics change |
Prefer a tag when it is unique, and data-testid for elements with no stable semantics. Avoid classes that exist only for styling, and avoid long structural paths like div > div > span:nth-child(2).
Absent elements
Elements inside @if or @for blocks do not exist until the condition is true. Use that in assertions. Check that the element is absent before the action, then present after it:
expect(root.querySelector('[data-testid="saved"]')).toBeNull();Assert on null rather than on textContent. Reading textContent of a missing element throws instead of failing the assertion cleanly.
Querying with DebugElement
DebugElement.query takes a predicate. By.css builds one from a selector, and By.directive matches elements that carry a directive.
import { By } from '@angular/platform-browser';
const buttonDebug = fixture.debugElement.query(By.css('button'));
const button: HTMLButtonElement = buttonDebug.nativeElement;query returns null when nothing matches, and queryAll returns an array. Choose By.directive(SomeDirective) when you want to find an element by the directive or child component on it, for example to reach a child component's instance through debugElement.componentInstance.
Reading what the user sees
Read text with textContent, and normalise it. Templates produce whitespace from line breaks and interpolation, so exact string equality is fragile.
const text = root.querySelector('[data-testid="saved"]')?.textContent?.trim();
expect(text).toBe('Saved Ada');For form controls, read properties rather than attributes. input.value, input.checked, and button.disabled reflect the live state. getAttribute('value') returns only what was in the markup, which is usually not what you want.
Triggering events
Calling native methods
For clicks, call the element's own method. HTMLElement.click() dispatches a real click event that bubbles, so listeners on the element and on its ancestors run.
button.click();
fixture.detectChanges();For other events, create an Event and dispatch it. Input handlers listen for input, so setting value alone does nothing. The browser only fires that event for real typing.
input.value = 'Ada';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();Two details matter here:
- Events created with
new Event('x')do not bubble by default. If the listener is on an ancestor (event delegation or a host listener on a parent), pass{ bubbles: true }. - Use the right event class when the handler reads event fields.
new KeyboardEvent('keydown', { key: 'Enter' })providesevent.key, andnew MouseEvent('click', { shiftKey: true })provides modifiers.
A complete test
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { NameFormComponent } from './name-form.component';
describe('NameFormComponent', () => {
function setup() {
const fixture = TestBed.createComponent(NameFormComponent);
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
return {
fixture,
root,
input: root.querySelector<HTMLInputElement>('input')!,
button: root.querySelector<HTMLButtonElement>('button')!,
};
}
it('disables Save until a name is typed', () => {
const { fixture, input, button } = setup();
expect(button.disabled).toBe(true);
input.value = 'Ada';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(button.disabled).toBe(false);
});
it('shows a confirmation after Save is clicked', () => {
const { fixture, root, input, button } = setup();
expect(root.querySelector('[data-testid="saved"]')).toBeNull();
input.value = 'Ada';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
button.click();
fixture.detectChanges();
const text = root.querySelector('[data-testid="saved"]')?.textContent?.trim();
expect(text).toBe('Saved Ada');
});
it('does not save when the disabled button is clicked', () => {
const { fixture, root, button } = setup();
button.click();
fixture.detectChanges();
expect(root.querySelector('[data-testid="saved"]')).toBeNull();
});
});The setup() function keeps each test independent. Every test gets a fresh fixture, so state from one test cannot leak into the next.
The third test shows a useful property of native events. The browser does not dispatch click on a disabled button, so the handler never runs. The test checks the same behavior a user would experience.
triggerEventHandler and its limits
DebugElement.triggerEventHandler(name, event?) calls the Angular listeners registered for that event on that element. It does not dispatch a DOM event. No capture or bubbling happens, no ancestors are notified, and browser rules such as the disabled button are not applied.
import { By } from '@angular/platform-browser';
const debugButton = fixture.debugElement.query(By.css('button'));
debugButton.triggerEventHandler('click');
fixture.detectChanges();If the button is disabled, this still runs submit(), and the test can pass while real users cannot reach that code. Use it when a native event is hard to build, or when you want to pass your own object as $event. Otherwise prefer native events.
| Approach | Real DOM event | Bubbles | Respects `disabled` | Works on non-DOM listeners |
|---|---|---|---|---|
| `element.click()` | Yes | Yes | Yes | No |
| `dispatchEvent(new Event(...))` | Yes | Only if set | Not for custom events | No |
| `triggerEventHandler` | No | No | No | Yes (Angular listeners) |
Common errors
- Forgetting
detectChanges()after the action. The handler ran and state changed, but the DOM still shows the old values. The assertion fails with stale text. CalldetectChanges()between the action and the assertion. - Holding a reference to a removed element. An element inside
@ifcan be destroyed and recreated. Query again afterdetectChanges()instead of reusing an old variable. - Setting
valuewithout dispatchinginput. The DOM changes, the component never hears about it, and the assertion on state fails. - Querying before the first
detectChanges(). The template has not rendered, soquerySelectorreturnsnull. - Asserting on structure instead of behavior. A test that counts
divlevels breaks on harmless refactors.
Exercise
A component renders <p data-testid="msg"> inside @if (show()). A test clicks a button that sets show to true, then runs expect(root.querySelector('[data-testid="msg"]')?.textContent).toContain('Hi'). It fails because the value is undefined. What is the most likely cause, and how do you fix it?
Show answer
The test did not call fixture.detectChanges() after the click, so the @if block was never rendered and querySelector returned null. Add fixture.detectChanges() between button.click() and the assertion.
Exercise
You test a delete button that is disabled while a request is running. A test using debugElement.triggerEventHandler('click') shows delete() being called while the button is disabled. Why does this differ from what a user experiences, and what would you use instead?
Show answer
triggerEventHandler calls the Angular listener directly and skips browser rules, so it ignores disabled. A user's click on a disabled button never fires. Use button.click() on the native element, which respects disabled, and assert that delete() was not called.