Sub topic 12
Testing the task service
This chapter adds unit tests for TaskService, the signal-based service from the earlier chapters. It assumes you know the TaskService code, basic describe/it/expect syntax, and how inject() and providedIn: 'root' work. You should also be able to run ng test in the project.
Why test the service first
TaskService holds all the app's state, and it has no template, DOM, or HTTP dependency. That makes it the cheapest place to catch bugs. Components only display what the service produces, so if the service is correct, most component bugs are display bugs.
The service also has behavior that is easy to break by accident:
nextIdmust increase on every add.togglemust change only the matching task.remainingmust stay in sync withtasks.- State must change by replacing the array, not by editing it in place.
How the test runs
TestBed builds a small dependency injection container for each test. Calling TestBed.inject(TaskService) asks that container for the service. Because the service uses providedIn: 'root', no provider setup is needed. Angular resets the container between tests, so every test receives a fresh TaskService with an empty list and nextId back at 1.
Signals are synchronous. After service.add('x') returns, service.tasks() already contains the new task, and service.remaining() already reflects it. You don't need await, fakeAsync, or change detection for this service.
The runner
ng test runs whichever runner your Angular version configured when you created the project. Depending on the version, that is Karma with Jasmine or Vitest. describe, it, beforeEach, expect, toBe, and toEqual work the same way in all of them, so the examples below don't depend on the runner. Check package.json and angular.json if you want to know which one you have.
A first test file
Put this in task.service.spec.ts, next to the service. Each test creates its own service instance through beforeEach.
import { TestBed } from '@angular/core/testing';
import { TaskService } from './task.service';
describe('TaskService', () => {
let service: TaskService;
beforeEach(() => {
service = TestBed.inject(TaskService);
});
it('starts with no tasks', () => {
expect(service.tasks()).toEqual([]);
expect(service.remaining()).toBe(0);
});
it('adds tasks with increasing ids', () => {
service.add('First');
service.add('Second');
expect(service.tasks()).toEqual([
{ id: 1, title: 'First', done: false },
{ id: 2, title: 'Second', done: false },
]);
expect(service.remaining()).toBe(2);
});
it('toggles a task and updates the remaining count', () => {
service.add('Write tests');
const id = service.tasks()[0].id;
service.toggle(id);
expect(service.tasks()[0].done).toBe(true);
expect(service.remaining()).toBe(0);
});
it('removes only the task with the given id', () => {
service.add('Keep');
service.add('Drop');
const dropId = service.tasks()[1].id;
service.remove(dropId);
expect(service.tasks().map(t => t.title)).toEqual(['Keep']);
});
});Notice that the tests call service.tasks() with parentheses. A signal is a function, so expect(service.tasks).toEqual([]) compares a function to an array and fails. This is one of the most common mistakes when you first test signals.
Why `toEqual` and not `toBe`
toBe checks identity (===). toEqual compares structure. Use toEqual for arrays and objects, because two separate arrays with the same contents are never ===. Use toBe for primitives such as the remaining() number and the done flag.
Testing immutability
The service promises to change state by replacing the array, not by editing it. Components that use OnPush change detection (a later chapter covers it) and computed values depend on that promise. A test can lock it in:
it('replaces the array instead of mutating it', () => {
service.add('Original');
const before = service.tasks();
const originalTask = before[0];
service.toggle(originalTask.id);
const after = service.tasks();
expect(after).not.toBe(before);
expect(originalTask.done).toBe(false);
expect(after[0].done).toBe(true);
});Three things are checked here. The list is a new array (not.toBe). The old task object was not edited (originalTask.done is still false). The new list holds an updated copy. If someone rewrites toggle as list.find(...).done = !..., this test fails, even though a simpler test that only reads tasks()[0].done would still pass.
The service exposes tasks through asReadonly(), so service.tasks.set([]) is a compile error. You can't test that with a normal expect, because the TypeScript compiler enforces it. If you ever make _tasks public by mistake, the compiler and the code review are your safety net.
Edge cases worth covering
Happy paths are not enough. These cases are cheap to write and document how the service behaves:
it('ignores toggle for an unknown id', () => {
service.add('Only task');
service.toggle(999);
expect(service.tasks()).toEqual([{ id: 1, title: 'Only task', done: false }]);
});
it('ignores remove for an unknown id', () => {
service.add('Only task');
service.remove(999);
expect(service.tasks().length).toBe(1);
});
it('never reuses an id after a removal', () => {
service.add('A');
service.add('B');
service.remove(2);
service.add('C');
expect(service.tasks().map(t => t.id)).toEqual([1, 3]);
});
it('counts only unfinished tasks in remaining', () => {
service.add('A');
service.add('B');
service.add('C');
service.toggle(2);
expect(service.remaining()).toBe(2);
});The id test matters because it shows that nextId is a plain counter, not list.length + 1. If a refactor changed it to use the list length, the removal in that test would produce a duplicate id, and the track task.id expression in @for would misbehave.
The service doesn't trim or validate titles. That is the form's job (TaskFormComponent trims and checks Validators.required). Test each rule where it lives. Don't add a "rejects empty title" test to the service unless you also add that behavior to the service.
Test isolation and shared state
Tests in this chapter rely on TestBed giving each test a new service. If a test passes alone but fails when the whole file runs, look for state that survives between tests. Common causes:
- A module-level variable that holds a service created outside
beforeEach. - A
staticcounter used for ids instead of the instance fieldnextId. - Calling
TestBed.injectonce at the top ofdescribeinstead of insidebeforeEachorit.
The last one is the easiest to hit. Code in the describe body runs when the file loads, before TestBed is reset for each test, so one service instance leaks across tests.
Testing the HTTP service
TaskApi returns Observables that do nothing until someone subscribes. In a test you don't want to hit a real server. Angular provides provideHttpClientTesting(), which replaces the network layer. HttpTestingController then lets the test inspect each request and supply the response.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Task } from './task';
import { TaskApi } from './task.api';
describe('TaskApi', () => {
let api: TaskApi;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
api = TestBed.inject(TaskApi);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => {
http.verify();
});
it('loads tasks with a GET request', () => {
let result: Task[] | undefined;
api.getTasks().subscribe(tasks => (result = tasks));
const req = http.expectOne('/api/tasks');
expect(req.request.method).toBe('GET');
req.flush([{ id: 1, title: 'From server', done: false }]);
expect(result).toEqual([{ id: 1, title: 'From server', done: false }]);
});
it('sends the title in a POST body', () => {
api.addTask('New').subscribe();
const req = http.expectOne('/api/tasks');
expect(req.request.method).toBe('POST');
expect(req.request.body).toEqual({ title: 'New' });
req.flush({ id: 5, title: 'New', done: false });
});
});Each part has a job:
subscribestarts the request. Without it,expectOnefails because no request was ever made.expectOnefinds exactly one matching request and fails if there are zero or several.flushsupplies the server's answer, and the subscriber's callback runs synchronously.http.verify()inafterEachfails the test if a request was made that the test never handled. It catches duplicate calls and forgotten flushes.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `expect(received).toEqual([])` fails with a function | Read the signal without calling it | Use `service.tasks()` |
| `NullInjectorError: No provider for HttpClient` | Test config missing HTTP providers | Add `provideHttpClient()` and `provideHttpClientTesting()` |
| Tests pass alone, fail together | Service created in the `describe` body or kept in a shared variable | Create the service in `beforeEach` |
| `expectOne` fails with "Expected one matching request, found none" | The Observable was never subscribed | Call `.subscribe()` before `expectOne` |
| Ids in expectations are off by one | Test assumed ids from another test's state | Rely on `TestBed` isolation and assert from id 1 |
Running the tests
ng testThe runner watches your files and reruns affected tests when you save. Press the quit key shown in the terminal, or add the single-run flag your Angular version documents, when you want a one-time run such as in continuous integration.
Exercise
Add a method clearCompleted() to TaskService that removes every task with done: true. Write a test that adds three tasks, toggles two of them, calls clearCompleted(), and checks both tasks() and remaining(). Which two assertions would you write, and why does remaining() not change?
Show answer
Implementation: clearCompleted(): void { this._tasks.update(list => list.filter(t => !t.done)); }. In the test, add 'A', 'B', and 'C', toggle ids 1 and 2, then call clearCompleted(). Assert expect(service.tasks()).toEqual([{ id: 3, title: 'C', done: false }]) and expect(service.remaining()).toBe(1). remaining() stays at 1 because it counts only unfinished tasks, and the removed tasks were all finished. The computed value recalculates automatically after the signal changes, but the result is the same number.
Exercise
A teammate writes const service = TestBed.inject(TaskService); in the body of describe, outside any beforeEach. Two tests each call service.add('x') and then expect service.tasks().length to be 1. One of them fails. Explain why, and give the fix.
Show answer
The describe body runs once when the file loads, so both tests share one service instance. The first test to run adds a task and passes. The second test then sees two tasks, so its length check of 1 fails. Move the TestBed.inject call into beforeEach (or into each it) so that TestBed creates a fresh service for every test.