Sub topic 12
What to Test and What to Leave Out
This chapter assumes you can already write a TestBed test, set inputs with setInput, read outputs, and replace a service with a provider. Here the question is which tests are worth writing, not how to write them. A suite with too many implementation-bound tests slows you down on every refactor. A suite that tests only the happy path misses real bugs.
Test behavior, not implementation
A component test should fail when something a user or a parent component can observe changes. It should not fail when you rename a private field or swap one signal API for another.
Take the CounterComponent from earlier chapters. Its count signal is protected, so the template can read it but outside code cannot. The first test below reaches past that boundary. The second checks only what the user sees.
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
it('BRITTLE: reads the internal signal', () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
fixture.componentInstance.increment();
expect((fixture.componentInstance as any).count()).toBe(1);
});
it('shows the new count after a click', () => {
const fixture = TestBed.createComponent(CounterComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();
const text = fixture.nativeElement.querySelector('[data-testid="count"]').textContent;
expect(text).toContain('Count: 1');
});
});If you later turn count into a computed() over an event list, or rename it to total, the first test breaks even though nothing visible changed. The second keeps passing. It also exercises the template binding, so it catches a typo in {{ count() }} that the first test cannot see.
The public contract of a component
Every component exposes a small contract. Write tests against these surfaces:
| Surface | What to assert | How |
|---|---|---|
| Rendered DOM | Text, presence or absence of elements, attributes the user relies on | `querySelector` after `detectChanges()` |
| Inputs | The DOM or outputs change when the input changes | `fixture.componentRef.setInput(...)` |
| Outputs | The right value is emitted at the right moment | Subscribe with `vi.fn()` |
| Injected collaborators | The component sends the data the collaborator needs | Mock via providers |
| Side effects at the boundary | Navigation, HTTP requests, storage writes | Router mock, `HttpTestingController` |
Everything not in this table, such as private methods, intermediate signals, and the order of internal calls, is an implementation detail. Cover it indirectly through the contract.
What to leave out
Skip tests that only confirm someone else's code works.
- Framework behavior. Do not test that
@forrenders one<li>per item, thatinput()accepts a value, or that(click)calls a method. The Angular team tests those. Your test ofUserListComponentshould check that your names appear, not that control flow works. - Third-party library internals. If a component wraps a date picker, test that you pass the right options and handle its events. Do not test that the picker opens.
- Trivial pass-through code. A getter that returns a field, or a template that only prints one string, rarely breaks on its own. A single rendering test covers it.
- Private methods. If a private method holds logic complicated enough to deserve its own tests, move it to a function or service and test that directly.
- Styling. Unit tests in jsdom do not do real layout. Check classes only when a class carries behavior, such as
aria-disabledor anis-errorstate that other code depends on. - Exact markup structure. Selectors like
div > div:nth-child(2) > spanbreak on harmless layout changes. Prefer a stable hook such asdata-testid, a role, or visible text.
Deciding where the boundary goes
Each test needs an answer to: what is real and what is fake? Make the unit under test and everything cheap and deterministic real. Replace anything slow, non-deterministic, or outside your control.
In practice:
- Mock: HTTP (use
HttpTestingControlleror a mocked service), timers, router navigation, browser APIs such aslocalStorage, and services that talk to other systems. - Keep real: pure helpers, small child components rendered inside the template, and signals and computed values. Mocking these makes the test pass while the real wiring is broken.
Over-mocking is a common failure. If a test replaces every collaborator and then asserts that each mock was called, it checks only that your code matches the way you wrote your mocks.
Asserting on mocks with care
Look again at the user list test:
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { describe, it, expect, vi } from 'vitest';
import { UserListComponent, UserService } from './user-list.component';
describe('UserListComponent', () => {
it('renders the users returned by the service', () => {
const list = vi.fn(() => of(['Ada', 'Grace']));
TestBed.configureTestingModule({
providers: [{ provide: UserService, useValue: { list } }],
});
const fixture = TestBed.createComponent(UserListComponent);
fixture.detectChanges();
const items = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('li'),
).map((li) => li.textContent);
expect(items).toEqual(['Ada', 'Grace']);
expect(list).toHaveBeenCalledTimes(1);
});
});The toEqual assertion checks the contract. The toHaveBeenCalledTimes(1) assertion is weaker. It would fail if you later cache the result or call list() from two places, even if the page still looks right. Keep a call-count assertion only when the count is the requirement, for example "must not re-request on every keystroke". Otherwise delete it.
Assertions on call arguments are more useful. If the component must send the search text to a service, expect(search).toHaveBeenCalledWith('ada') checks a real obligation to a collaborator.
Where the effort pays off
Spend test effort where bugs hide.
- Boundary and default values. The
stepinput defaults to1. A test that never sets it proves the default works:
import { TestBed } from '@angular/core/testing';
import { describe, it, expect, vi } from 'vitest';
import { CounterComponent } from './counter.component';
describe('CounterComponent defaults', () => {
it('adds 1 per click when step is not set', () => {
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();
button.click();
expect(onChanged).toHaveBeenNthCalledWith(1, 1);
expect(onChanged).toHaveBeenNthCalledWith(2, 2);
});
});- Empty and missing data. Render
UserListComponentwithof([])and assert that no<li>exists. Empty states are where templates throw or show broken text. - State transitions. Test sequences, not only single actions. Two clicks cover accumulation, which a single click cannot show.
- Error paths you have designed. The
UserListComponentabove has no error handling, andtoSignalrethrows an observable's error when the signal is read. There is no error behavior to test yet. Decide what the user should see on failure first, then write that test. - Debounce, cancellation, and ordering. These are the cases from the fake-timer chapter, where a wrong implementation looks fine in a manual click-through.
Keeping tests cheap to maintain
- Name tests by outcome. "Emits the last value after 300 ms" tells you what broke. "Works" does not.
- Share setup, not assertions. A
setup()helper that creates the fixture is fine. A helper that hides theexpectcalls makes failures hard to read. - Use one scenario per test, with several related assertions if needed. Checking both the rendered text and the emitted value after a single click is reasonable. Chaining unrelated flows into one test hides which one failed.
- Avoid snapshot tests of whole component HTML. Any markup change fails them, and people learn to update them without reading the diff.
- Treat coverage as a smoke detector. A line with no coverage deserves a question. A high percentage does not show the tests are good. A test with no assertions raises coverage and proves nothing.
Quick checklist
Before keeping a test, ask:
- Does it fail if the user-visible behavior breaks?
- Does it survive renaming a private field or reordering internal calls?
- Is each mock standing in for something slow, random, or external?
- Would a failure message tell a teammate what went wrong?
Exercise
A teammate writes a test for UserListComponent that (a) asserts the rendered names, (b) asserts that UserService.list was called exactly once, and (c) reads the private names signal through fixture.componentInstance['names'](). Which of the three would you keep, which would you change or remove, and why?
Show answer
Keep (a), because it checks what the user sees and survives refactors. Remove (c), because it reads an internal signal and breaks on a rename or an implementation change even though the page is unchanged; (a) already covers it. Remove or relax (b) unless a single request is a stated requirement. A call-count assertion fails on harmless changes such as caching or moving the call, and it adds no information beyond (a). If the requirement is that the service is called with specific arguments, assert toHaveBeenCalledWith instead.
Exercise
Name two behaviors of SearchBoxComponent that deserve tests, and one thing you would not test.
Show answer
Worth testing: it emits only the last value after the 300 ms delay (not after 299 ms), and rapid input replaces earlier pending values instead of emitting each one. Not worth testing: that setTimeout or clearTimeout works, or the private timer field. Those are platform behavior and an implementation detail.