Sub topic 6
Querying the DOM and triggering events
This chapter assumes you can create a component with TestBed.createComponent and call fixture.detectChanges(), as covered in the previous two chapters. You should also know basic querySelector usage.
Test what the user sees
A component test should act like a user: find an element, interact with it, and check what appears on screen. The fixture gives you two ways to reach the rendered template.
| API | Returns | Best for |
|---|---|---|
| `fixture.nativeElement` | The host `HTMLElement` | Plain DOM queries and real events |
| `fixture.debugElement` | Angular's `DebugElement` wrapper | Angular-aware queries such as `By.directive` |
Prefer nativeElement. It uses standard DOM APIs, so your tests read like browser code and keep working if you later run them in a real browser.
Querying elements
Call querySelector for one element and querySelectorAll for several. querySelector returns null when nothing matches, so assert that the element exists before you use it.
Select by something stable. A data-testid attribute, a role, or an element type survives restyling. A CSS class or a position in the list does not.
const button = fixture.nativeElement.querySelector('button') as HTMLButtonElement | null;
expect(button).not.toBeNull();Triggering events
Use real DOM events. For a click, call button.click(). For other events, create an Event and call dispatchEvent. After any event, call fixture.detectChanges() so the template re-renders.
The component below reads text from an input and shows a greeting.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-greeter',
template: `
<label>Name <input type="text" (input)="onInput($event)" /></label>
<button type="button" (click)="clear()">Clear</button>
<p data-testid="greeting">Hello, {{ name() || 'stranger' }}</p>
`,
})
export class GreeterComponent {
protected readonly name = signal('');
protected onInput(event: Event) {
this.name.set((event.target as HTMLInputElement).value);
}
protected clear() {
this.name.set('');
}
}The test types into the input, clicks the button, and checks the greeting after each step.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { GreeterComponent } from './greeter.component';
describe('GreeterComponent', () => {
it('greets the typed name and resets on clear', () => {
const fixture = TestBed.createComponent(GreeterComponent);
fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
const input = root.querySelector('input') as HTMLInputElement;
const button = root.querySelector('button') as HTMLButtonElement;
const greeting = () => root.querySelector('[data-testid="greeting"]')!.textContent;
expect(greeting()).toContain('Hello, stranger');
input.value = 'Ada';
input.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(greeting()).toContain('Hello, Ada');
button.click();
fixture.detectChanges();
expect(greeting()).toContain('Hello, stranger');
});
});The greeting helper is a function, not a stored value. It re-queries the DOM on each call, so it always reflects the latest render.
Common errors
- Stale DOM. If an assertion shows the old text, you probably forgot
detectChanges()after the event. - Setting
valuewithout an event. Assigninginput.valuedoes not run the(input)handler. You must also dispatch the event. - Wrong event name. A handler bound to
(change)ignores aninputevent. Dispatch the event the template listens for. - A null query result. Add
detectChanges()before querying if the element sits behind@ifor is not yet rendered.
Exercise
A test sets input.value = 'Grace' and calls fixture.detectChanges(), but the greeting still reads "Hello, stranger". Why, and how do you fix it?
Show answer
Assigning value does not fire an event, so the (input) handler never ran and the signal did not change. Dispatch the event with input.dispatchEvent(new Event('input')) before calling fixture.detectChanges().