Sub topic 12
Testing the task service
This chapter assumes you have the TaskService from the earlier chapters, working knowledge of TypeScript, and a project created with the Angular CLI. You should also know what a signal and a computed signal are. If you used the default ng new setup, the test runner and the describe, it, and expect functions are already configured.
Why test the service first
The service holds all of the app's state. Components only display it and forward user actions to it. A test of the service therefore covers the rules that matter most: adding, toggling, and removing tasks, and the remaining count. The test needs no browser, no template, and no component.
Getting the service from TestBed
TestBed is Angular's testing utility. It builds a small dependency injection environment for each test. TaskService is declared with providedIn: 'root', so you don't register it by hand. Call TestBed.inject(TaskService) and you get an instance.
import { TestBed } from '@angular/core/testing';
import { TaskService } from './task.service';
describe('TaskService', () => {
it('toggles a task and updates the remaining count', () => {
const service = TestBed.inject(TaskService);
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);
});
});The test follows three steps, often called arrange, act, and assert:
- Arrange: get the service and add one task.
- Act: call
togglewith that task's id. - Assert: read the signal and the computed value, and compare them with what you expect.
Signals are read by calling them, so you write service.tasks() and service.remaining(). The computed value is up to date as soon as you read it. You don't need to wait or trigger anything.
Running the tests
Run the tests from the project folder:
ng testThe command compiles the spec files and runs them in watch mode. It reruns the affected tests when you save a file.
Each test gets a fresh service
TestBed resets between tests. Each it block calls TestBed.inject and gets a new TaskService, with an empty list and nextId back at 1. Tests therefore don't affect each other, and you can rely on that when you write assertions about ids.
Adding more cases
One test is not enough. Add a test for each rule the service enforces. Keep each test small and name it after the behavior it checks.
import { TestBed } from '@angular/core/testing';
import { TaskService } from './task.service';
describe('TaskService rules', () => {
it('starts with no tasks', () => {
const service = TestBed.inject(TaskService);
expect(service.tasks()).toEqual([]);
expect(service.remaining()).toBe(0);
});
it('adds tasks with increasing ids', () => {
const service = TestBed.inject(TaskService);
service.add('First');
service.add('Second');
expect(service.tasks().map(t => t.id)).toEqual([1, 2]);
});
it('removes a task by id', () => {
const service = TestBed.inject(TaskService);
service.add('First');
service.add('Second');
service.remove(1);
expect(service.tasks().map(t => t.title)).toEqual(['Second']);
});
});Common errors
- Forgetting the parentheses.
expect(service.tasks).toBe(...)compares the signal function itself, not its value. Writeservice.tasks(). - Assuming a shared instance across tests. Because
TestBedresets, state from one test never carries into the next. Add the tasks each test needs inside that test. - Testing through the private signal.
_tasksis private. Test through the publictasksview and the methods, which is how components use the service. - Mutating results. The service replaces the array on every change. If a test keeps a reference to the old array, that reference does not change after a later
add. Readservice.tasks()again after each action.
Exercise
Write a test that adds two tasks, toggles only the first one, and checks that remaining() equals 1. Which line reads the count, and why are parentheses needed?
Show answer
Use service.add('A'); service.add('B'); service.toggle(service.tasks()[0].id); expect(service.remaining()).toBe(1);. The line service.remaining() reads the count. A computed value is a function, so you must call it to get the current number. Without the parentheses you compare the function itself.
Exercise
Why does a test that adds a task and expects id to be 1 still pass when it runs after another test that also added tasks?
Show answer
TestBed creates a fresh TaskService for each test, so nextId starts at 1 again and the list starts empty. State from earlier tests doesn't carry over.