Sub topic 7
Testing inputs and outputs
This chapter covers how to drive a component's public API from a test. You set signal inputs with setInput, read outputs by subscribing to them, and check both the rendered DOM and the emitted values. It assumes you can already create a component with TestBed, call fixture.detectChanges(), and query the DOM. It also assumes you know input(), output(), and signal().
Why inputs and outputs are the contract
A component's inputs and outputs are its public contract with a parent. Inputs carry data in. Outputs carry events out. Tests that exercise only this contract keep working when you rename a private field or restructure the template internals.
Here is the counter component used throughout this chapter.
import { Component, input, output, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p data-testid="count">Count: {{ count() }}</p>
<button type="button" (click)="increment()">Add</button>
`,
})
export class CounterComponent {
readonly step = input(1);
readonly changed = output<number>();
protected readonly count = signal(0);
increment() {
this.count.update((c) => c + this.step());
this.changed.emit(this.count());
}
}It has one input (step), one output (changed), and one piece of internal state (count). The count signal is protected, so a test cannot read it directly. The test observes it through the rendered text, which is what a user sees.
Setting inputs with setInput
A signal input created with input() is read-only from the outside. Writing fixture.componentInstance.step = ... does not compile, and step.set(...) does not exist. Angular sets inputs through the component's ComponentRef, and the fixture exposes it as fixture.componentRef.
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', 5);
fixture.detectChanges();setInput takes the input's public name and the new value. It works the same way a parent's template binding does. It also works for inputs declared with the older @Input() decorator, so you can use one technique across a codebase that mixes both styles.
Two details matter in practice:
setInputmarks the component as needing a check, but it does not run change detection. The new value reaches the template only after the nextfixture.detectChanges().- Required inputs (
input.required<T>()) throw when read before a value exists. CallsetInputbefore the firstdetectChanges(), or the first render fails with an error about reading a required input too early.
Aliases and transforms
If an input has an alias, setInput uses the alias, which is the name a parent would write in its template.
import { booleanAttribute, Component, input } from '@angular/core';
@Component({
selector: 'app-badge',
template: `@if (highlighted()) { <strong>{{ label() }}</strong> } @else { {{ label() }} }`,
})
export class BadgeComponent {
readonly label = input.required<string>();
readonly highlighted = input(false, {
alias: 'highlight',
transform: booleanAttribute,
});
}import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { BadgeComponent } from './badge.component';
describe('BadgeComponent', () => {
it('applies the input transform and alias', () => {
const fixture = TestBed.createComponent(BadgeComponent);
fixture.componentRef.setInput('label', 'New');
fixture.componentRef.setInput('highlight', '');
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('strong')?.textContent).toBe('New');
});
});The empty string passed to highlight is what <app-badge highlight> produces in a template. booleanAttribute turns it into true. Passing the alias, not the property name highlighted, is what makes the test match real usage.
Testing outputs
An output() returns an OutputEmitterRef. It has a subscribe method, so a test attaches a listener and records what arrives. A vi.fn() mock makes a convenient listener because it records every call and its arguments.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect, vi } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
it('adds the step to the count and emits the new value', () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.componentRef.setInput('step', 5);
const onChanged = vi.fn();
fixture.componentInstance.changed.subscribe(onChanged);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
const text = fixture.nativeElement.querySelector('[data-testid="count"]').textContent;
expect(text).toContain('Count: 5');
expect(onChanged).toHaveBeenCalledWith(5);
});
});The test follows a fixed order:
- Create the fixture.
- Set inputs.
- Subscribe to outputs.
- Run the first
detectChanges(). - Act on the DOM.
- Run
detectChanges()again. - Assert on the DOM and on the listener.
Subscribing before the action matters. An output does not replay earlier emissions to late subscribers, so a listener attached after the click sees nothing.
Checking the emission, not only the call
toHaveBeenCalledWith(5) confirms the payload. Other matchers cover related cases:
| Question | Matcher |
|---|---|
| Did it emit at all? | `expect(fn).toHaveBeenCalled()` |
| Did it emit exactly once? | `expect(fn).toHaveBeenCalledTimes(1)` |
| Did it emit nothing? | `expect(fn).not.toHaveBeenCalled()` |
| What was the payload of the first or last call? | `toHaveBeenNthCalledWith(1, x)` or `toHaveBeenLastCalledWith(x)` |
| Were the calls in a given sequence? | `expect(fn.mock.calls).toEqual([[1], [2]])` |
For an object payload, toHaveBeenCalledWith compares by deep equality, so you can pass an object literal.
Stopping a subscription
subscribe on an output returns an OutputRefSubscription with an unsubscribe() method. In a short test you rarely need it, because TestBed destroys the fixture at the end of each test and Angular cleans up the output's listeners. Call unsubscribe() only when the test itself needs to prove that emissions stop.
Testing the effect of an input change
Inputs usually change over time. A test can call setInput several times on one fixture to show that the component reacts. After each call, run detectChanges().
import { TestBed } from '@angular/core/testing';
import { describe, it, expect, vi } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent step input', () => {
it('uses the latest step on every click', () => {
const fixture = TestBed.createComponent(CounterComponent);
const onChanged = vi.fn();
fixture.componentInstance.changed.subscribe(onChanged);
fixture.detectChanges();
const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
button.click();
fixture.componentRef.setInput('step', 10);
fixture.detectChanges();
button.click();
expect(onChanged.mock.calls).toEqual([[1], [11]]);
});
});The first click uses the default step of 1. After setInput('step', 10), the second click adds 10 to the running total of 1, so the output emits 11. The test reads the emitted values from mock.calls, which avoids a second DOM query.
Testing through a host component
setInput is the right default, but it skips the parent's template. A host component is a small component declared in the test file that renders the component under test with real bindings. Use one when the binding itself is what you want to verify: content projection, a two-way binding with model(), or an output handler wired in a template.
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
@Component({
imports: [CounterComponent],
template: `
<app-counter [step]="step()" (changed)="last.set($event)" />
<p data-testid="last">{{ last() }}</p>
`,
})
class HostComponent {
readonly step = signal(2);
readonly last = signal<number | null>(null);
}
describe('CounterComponent in a host', () => {
it('passes the bound step in and the emitted value out', () => {
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('[data-testid="last"]').textContent).toBe('2');
fixture.componentInstance.step.set(7);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('[data-testid="last"]').textContent).toBe('9');
});
});Here the test changes the parent's signal, not the child's input. The binding carries the change into the child. The host's last signal records what the child emitted, so the assertion reads the host's DOM. This verifies the wiring that setInput would skip.
The cost is extra code and a looser focus. Prefer setInput for the component's own logic and keep host components for binding behavior.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The DOM shows the old value after `setInput` | `detectChanges()` was not called afterward | Call `fixture.detectChanges()` after each `setInput` |
| `NG0950` error about reading a required input | A required input was read before it had a value | Call `setInput` for it before the first `detectChanges()` |
| The output listener is never called | The listener was attached after the emission | Subscribe before the click or method call |
| `setInput` throws that the input does not exist | The name is the property name, not the alias, or it is misspelled | Use the public (aliased) input name |
| The assertion passes but the DOM looks stale | The test read the DOM before the second `detectChanges()` | Re-run change detection, then query |
| A value of the wrong type arrives in the component | The input has a `transform` that you forgot to account for | Pass the raw value a template would pass |
What to assert
Choose assertions that a user or a parent component would notice:
- Assert on rendered text and attributes for what the template does with an input.
- Assert on output payloads for what the parent receives.
- Avoid asserting on
protectedorprivatemembers, and avoid callingincrement()directly when a click reaches the same code. Clicking the button also proves the template is wired to the method.
Calling a method directly is acceptable when the method is part of the public API and no template event reaches it.
Exercise
A test sets fixture.componentRef.setInput('step', 3), clicks the button, and then checks that the emitted value is 3. The component is correct, but the test fails because the listener was never called. The test code is:
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const onChanged = vi.fn();
fixture.componentInstance.changed.subscribe(onChanged);
fixture.componentRef.setInput('step', 3);
Name the problems and give the corrected order of steps.
Show answer
Two problems. First, the listener is subscribed after the click, and an output does not replay earlier emissions, so onChanged never sees the event. Second, setInput is called after the click, so the click used the default step of 1, not 3. The corrected order is: create the fixture, call setInput('step', 3), subscribe onChanged, call detectChanges(), click the button, call detectChanges(), then assert expect(onChanged).toHaveBeenCalledWith(3).
Exercise
When would you test a component through a host component instead of using setInput? Give one concrete case.
Show answer
Use a host component when the binding in a parent template is the behavior under test, for example when a parent wires (changed)="last.set($event)" and you want to prove that the emitted value reaches the parent's state, or when you test a two-way model() binding or content projection. setInput skips the parent's template, so it cannot show that the binding works.