Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 74 ยท Quality and Performance

Testing Components and Services

Test Angular components, signals and services with TestBed, ComponentFixture, HttpTestingController and harnesses, and practice with a mini test runner.

Tests are what let you change code on Friday afternoon without fear. Angular was designed with testing in mind: dependency injection means a test can swap a real service for a fake one, and the framework ships the tools to create components, trigger change detection and intercept HTTP calls without a server. This lesson shows what those tools are, how to test signals, services and HTTP, and what to test in the first place.

The real Angular test code is read-only, because the site cannot run the Angular compiler, TestBed or a browser test runner. The runnable examples use a mini test runner (describe, it, expect) written in about forty lines, and test plain logic and a fake HttpTestingController stand-in. The skills carry over: the real runners use the same describe/it/expect shape.

What to test, and what not to

A good Angular test suite is mostly about behavior a user or another developer relies on, not about the framework's internals. Roughly:

  • Pure logic (formatting, calculations, validators, reducers): plain unit tests, no TestBed at all. They are the fastest and the most valuable.
  • Services: create them through TestBed when they use inject(), with fakes for their dependencies.
  • Components: render them, interact like a user (click, type) and assert on the DOM. Check what the user sees, not private fields.
  • Integration of a few pieces: a component with a real service and a fake HTTP backend.
flowchart TB
  E["Few end-to-end tests<br/>(real browser, real server)"]
  C["Some component and integration tests<br/>(TestBed, DOM)"]
  U["Many unit tests<br/>(pure functions, services)"]
  U --> C --> E

A healthy suite is wide at the bottom: many fast unit tests, fewer component tests, very few end-to-end tests.

The test runner in 2025+ Angular

Tests need a runner that finds *.spec.ts files and executes them. Historically ng new generated Jasmine tests run by Karma in a real Chrome. Karma has been deprecated, and newer CLI versions steer new projects towards Vitest, run through the CLI's own unit-test builder; check what ng new generates in your version, because the status has been changing from release to release. Jest is not supported out of the box.

For daily writing the difference is small: describe, it, beforeEach and expect(...).toBe(...) exist in both. They differ mainly in how you make fakes (jasmine.createSpyObj and spyOn versus vi.fn() and vi.spyOn). ng test runs the suite.

TestBed and ComponentFixture

TestBed is Angular's test-time module. You configure it with the same things an app configures (imports, providers) and then ask it for components and services. For a standalone component, you put the component itself in imports:

TypeScript
import { Component, computed, signal } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';

@Component({
  selector: 'app-counter',
  template: `
    <button type="button" (click)="increment()">Add</button>
    <p class="doubled">{{ doubled() }}</p>
  `,
})
export class CounterComponent {
  readonly count = signal(0);
  readonly doubled = computed(() => this.count() * 2);

  increment(): void {
    this.count.update((n) => n + 1);
  }
}

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({ imports: [CounterComponent] }).compileComponents();
    fixture = TestBed.createComponent(CounterComponent);
    fixture.detectChanges(); // first render
  });

  it('shows the doubled count after a click', () => {
    const root: HTMLElement = fixture.nativeElement;

    root.querySelector('button')!.click();
    fixture.detectChanges();

    expect(root.querySelector('.doubled')!.textContent).toBe('2');
  });
});

The ComponentFixture wraps the created component. Its useful members:

  • fixture.componentInstance is the class instance.
  • fixture.nativeElement is the host DOM element, for querySelector.
  • fixture.debugElement is Angular's wrapper, handy for query(By.css(...)) and triggerEventHandler.
  • fixture.detectChanges() runs change detection so the DOM catches up with the state. In a classic (zone-based) test, nothing renders until you call it.
  • await fixture.whenStable() waits for pending asynchronous work such as resolved promises.

If your app is zoneless, tests should be too: add provideZonelessChangeDetection() to the TestBed providers and use await fixture.whenStable() instead of calling detectChanges() over and over.

Inputs, signals and effects

Setting an input directly on the instance (fixture.componentInstance.name = 'x') does not work with signal inputs, since input() is read-only. Use the fixture's component reference, which goes through the same mechanism a parent template would:

TypeScript
fixture.componentRef.setInput('title', 'Angular 101');
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('Angular 101');

Testing a signal is simple, because reading is synchronous and needs no subscription: call component.count.set(5) and check component.doubled() straight away. A computed is recomputed on read.

Effects are different: they run later, when Angular flushes them during change detection. In a test, call fixture.detectChanges() or, outside a component, TestBed.tick() (in older versions the method was TestBed.flushEffects()) before asserting on what an effect did.

Testing services and fakes

A service that uses inject() needs an injection context, which TestBed.inject provides. Replace dependencies by listing a fake in providers:

TypeScript
import { TestBed } from '@angular/core/testing';

describe('CartService', () => {
  let service: CartService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [{ provide: PriceApi, useValue: { priceOf: () => 10 } }],
    });
    service = TestBed.inject(CartService);
  });

  it('adds up item prices', () => {
    service.add('apple');
    service.add('pear');
    expect(service.total()).toBe(20);
  });
});

Every test gets a fresh TestBed, so a singleton service never leaks state from one test into the next. Prefer small hand-written fakes over elaborate mocking; if a fake is hard to write, the service probably has too many dependencies.

Testing HTTP

Never let a unit test talk to a real server. Angular's HttpTestingController replaces the network: your code makes a request, the test finds it, checks it and supplies a response by hand.

TypeScript
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

describe('CourseService', () => {
  let http: HttpTestingController;
  let service: CourseService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(), provideHttpClientTesting()],
    });
    service = TestBed.inject(CourseService);
    http = TestBed.inject(HttpTestingController);
  });

  afterEach(() => http.verify()); // fail if a request was never answered

  it('loads courses', () => {
    let result: Course[] | undefined;
    service.load().subscribe((courses) => (result = courses));

    const req = http.expectOne('/api/courses');
    expect(req.request.method).toBe('GET');
    req.flush([{ id: 1, title: 'Angular' }]);

    expect(result).toEqual([{ id: 1, title: 'Angular' }]);
  });

  it('reports server errors', () => {
    let message = '';
    service.load().subscribe({ error: (e) => (message = e.message) });

    http.expectOne('/api/courses').flush('boom', { status: 500, statusText: 'Server Error' });

    expect(message).toContain('500');
  });
});

provideHttpClient() goes first and provideHttpClientTesting() after it. expectOne fails if there is no matching request (or more than one), flush supplies the body, and verify() in afterEach catches requests you forgot to answer. Interceptors registered with withInterceptors still run in such a test, which is useful for checking that the auth header is added.

Component harnesses

Tests that dig for CSS classes break whenever markup changes. A component harness is a small class that knows how to find and operate a component, published by the component's author. Angular Material ships harnesses for its widgets:

TypeScript
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatButtonHarness } from '@angular/material/button/testing';

it('clicks the save button', async () => {
  const loader = TestbedHarnessEnvironment.loader(fixture);
  const button = await loader.getHarness(MatButtonHarness.with({ text: 'Save' }));
  await button.click();
  expect(fixture.componentInstance.saved()).toBe(true);
});

The calls are asynchronous because harnesses also run in real browsers. You can write harnesses for your own components, which pays off for widely used ones: when the markup changes, you update one class instead of fifty tests.

A runnable mini test runner

This stand-in is a complete little test framework: describe groups tests, it registers them, beforeEach resets state, and expect offers toBe, toEqual and toThrow. The runner reports each result. One function has a deliberate bug (the average of an empty list), so you can see what a failing test looks like.

TypeScript Stand-in: a mini test runner finding a bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The average([]) test fails with expected NaN to be 0, which is a real bug a test caught: dividing by zero. The fix would be to return 0 for an empty list, and the test would then pass. Also note the beforeEach that builds a new cart: that is the same discipline TestBed gives you, and it is why the "does not leak state" test passes.

A runnable HttpTestingController stand-in

Here the service depends on a backend object, and the test uses a fake HttpTestingController with the same three-step shape as the real one: the service makes a request, the test calls expectOne, inspects it and flushes a response, and verify() fails if something was never answered.

TypeScript Stand-in: expectOne, flush and verify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The last two scenarios show why verify() and expectOne matter: a test that quietly ignores an outstanding or missing request would pass while the code under test is wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a signal input need fixture.componentRef.setInput() in tests?

    input() returns a read-only signal. Setting it through componentRef.setInput goes through the same mechanism a parent binding uses, and the DOM updates on the next detectChanges.
  2. 2. What is the purpose of http.verify() in afterEach?

    verify() asserts that no requests are left open. Without it, a forgotten flush would pass silently.
  3. 3. Which code should you test with plain unit tests, with no TestBed?

    Pure logic needs no Angular machinery. Those tests are the fastest and the least brittle.
  4. 4. A test sets a signal that an effect watches, then immediately asserts on the effect's result and fails. What is the likely fix?

    Effects run when Angular flushes them during change detection, not synchronously at set(). Trigger that flush before asserting.
  5. 5. Why do component harnesses make tests less brittle?

    Tests that call harness methods like click() do not depend on CSS classes or element structure, which are the things that change most.

Summary

  • Test pure logic with plain unit tests, services through TestBed.inject with fakes in providers, and components through the DOM, the way a user sees them.
  • TestBed.createComponent gives a ComponentFixture; call fixture.detectChanges() (or await fixture.whenStable() in zoneless apps) to render. Set signal inputs with fixture.componentRef.setInput().
  • Read signals directly in tests; flush effects with change detection or TestBed.tick() before asserting on their results.
  • Use provideHttpClient() plus provideHttpClientTesting(), then expectOne, flush and verify() to test HTTP without a network.
  • Harnesses wrap a component's UI so tests do not depend on markup.
  • Runner status changes between versions (Karma deprecated, Vitest in newer CLIs); check what ng new generates for you.
  • The Angular code is read-only; the mini runner and fake HTTP controller are stand-ins.

Next: SSR, Hydration and Prerendering