Component Testing

TestBed Builds the Component for You

Component Testing

TestBed renders a component into a host DOM you can query and assert against — like a tiny in-memory browser.

4 min read Level 3/5 #angular#testing#components
What you'll learn
  • Use TestBed.createComponent to render a component
  • Use fixture.detectChanges and fixture.whenStable
  • Query elements with By.css and dispatch DOM events

Component tests render real DOM, set signal inputs, and assert against rendered output. The workhorse is TestBed.createComponent.

Render a Component

import { TestBed } from '@angular/core/testing';
import { GreetingComponent } from './greeting.component';

it('renders the name', () => {
  TestBed.configureTestingModule({ imports: [GreetingComponent] });

  const fix = TestBed.createComponent(GreetingComponent);
  fix.componentRef.setInput('name', 'Ada');
  fix.detectChanges();

  const el = fix.nativeElement.querySelector('h1');
  expect(el.textContent).toContain('Ada');
});

setInput is the canonical way to pass a signal input. detectChanges flushes the template so the DOM reflects the new state.

Query and Click

By.css lets you grab debug elements with selectors, perfect for triggering events.

import { By } from '@angular/platform-browser';

it('increments on click', () => {
  const fix = TestBed.createComponent(CounterComponent);
  fix.detectChanges();

  const btn = fix.debugElement.query(By.css('button'));
  btn.triggerEventHandler('click');
  fix.detectChanges();

  expect(fix.componentInstance.count()).toBe(1);
});

triggerEventHandler skips the real DOM event system — fast and reliable.

Async Work

When a component awaits something, use whenStable (or fakeAsync + tick) to wait.

it('loads users', async () => {
  const fix = TestBed.createComponent(UsersComponent);
  fix.detectChanges();
  await fix.whenStable();
  fix.detectChanges();

  expect(fix.nativeElement.querySelectorAll('li').length).toBe(3);
});

For a more behavior-focused alternative, try @testing-library/angular — it nudges you toward DOM-centric assertions and away from internals.

End-to-End Testing →