Unit testing components with TestBed

Intermediate · 8 min

Constructing a component in isolation for testing, querying its rendered DOM, and manually triggering change detection.

Before thisComponent basics and the @Component decorator

Web Tech Talk · 8 min

Unit testing components with TestBed

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Tech TalkReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • TestBed assembles a small, isolated Angular environment for a test — a real injector, a real component instance, a real (if minimal) change-detection cycle — without bootstrapping the whole app.
  • A component's bindings don't update in a test until you explicitly call `fixture.detectChanges()` — change detection isn't running automatically the way it does in a real, running app.
  • Querying the rendered DOM through `fixture.debugElement` (or the native element it wraps) is how a test verifies what a user would actually see, rather than only checking the component class's internal properties.

Testing a component means constructing one without the whole app

A component, in a real app, exists inside a fully bootstrapped Angular application — injected dependencies, a running change-detection loop, an actual place in the DOM. A test needs almost all of that same machinery, just scaled down to exactly one component, constructed and torn down fresh for each test. TestBed is the API that assembles that scaled-down environment.

describe('CounterComponent', () => {
  let fixture: ComponentFixture<CounterComponent>;
  let component: CounterComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({ imports: [CounterComponent] });
    fixture = TestBed.createComponent(CounterComponent);
    component = fixture.componentInstance;
  });

  it('increments on button click', () => {
    fixture.nativeElement.querySelector('button').click();
    fixture.detectChanges();
    expect(fixture.nativeElement.textContent).toContain('Count: 1');
  });
});

TestBed.configureTestingModule sets up a real (if minimal) injector for the test — the same dependency-injection mechanism from earlier in this roadmap, just scoped to whatever this one test needs rather than the whole app. TestBed.createComponent actually constructs an instance, giving you back a ComponentFixture — a handle on both the component instance itself (fixture.componentInstance) and its rendered output (fixture.nativeElement).

Change detection doesn’t run on its own inside a test

This is the detail that trips people up first: setting a property directly on component doesn’t update the rendered DOM until you explicitly call fixture.detectChanges(). In a running app, something — a click, zone.js’s notification, a signal read in the template — eventually triggers a change-detection pass automatically. Inside a test, nothing runs on its own; you’re in full manual control, which is deliberate — it means a test’s assertions happen at an exact, predictable moment you chose, not whenever Angular’s own scheduling happens to get around to it.

component.count = 5; // the class property changes
fixture.detectChanges(); // now the template actually re-renders to reflect it
expect(fixture.nativeElement.textContent).toContain('5');

Querying the DOM, not just the class

The reason these tests query fixture.nativeElement (or fixture.debugElement, a richer wrapper around the same rendered output) rather than only asserting on the component class’s properties is worth being explicit about: a component’s internal state can be entirely correct while whatever actually renders is still wrong — a template typo, a binding that targets the wrong property, a conditional that’s inverted. Testing the rendered output is what actually verifies the thing a real user would see, which is the thing that ultimately matters; checking only component.count === 5 would miss a template that never displays count at all.

Isolating a component from its real dependencies

A component injecting a real service — one that itself makes HTTP calls, say — drags that whole dependency chain into what’s supposed to be a focused unit test. TestBed.configureTestingModule’s providers array lets you substitute a fake in its place, the same useClass/useValue provider mechanism from the dependency-injection lessons earlier in this roadmap:

TestBed.configureTestingModule({
  imports: [UserCardComponent],
  providers: [{ provide: UserService, useValue: { getUser: () => of(mockUser) } }],
});

The component under test never knows the difference — it injects UserService exactly as it would in production, and gets the fake instead, with no real HTTP call anywhere near the test.

This lesson’s video builds component tests with TestBed from scratch, covering exactly this fixture/detectChanges/query rhythm; the linked “deeper” video is a substantially longer full testing course, useful once the TestBed basics here are solid and you want to go further into mocking dependencies and testing services.

Check yourself

  1. 01After setting `component.count = 5` directly on a component instance inside a test, why might `fixture.nativeElement.textContent` still show the old value?

    Because change detection hasn't run since that assignment — in a real app, some trigger (an event, zone.js's notification, a signal change) would eventually cause a re-check, but inside a test, nothing runs automatically. Calling `fixture.detectChanges()` is what actually re-evaluates the template's bindings against the component's current state and updates the rendered DOM to match.

  2. 02Why does testing a component by rendering it and querying its DOM output catch bugs that only checking the component class's properties directly would miss?

    A component's class properties can be entirely correct while its template still renders wrong — a typo in a binding expression, a missing `*ngIf` condition, an incorrectly bound attribute. Querying the actual rendered DOM verifies what a user would really see, which is the thing that ultimately matters; checking only the class's internal state can pass while the visible output is still broken.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark