Sub topic 1
What a Service Test Should and Should Not Cover
A service test costs time to write and time to maintain. It pays off only when it checks behavior that matters and still passes after harmless changes. This chapter helps you decide what to test in an Angular service before you write any test code. The later chapters cover the mechanics: TestBed, stubs, and HttpTestingController.
Prerequisites
This chapter assumes you already know:
- TypeScript basics, including classes, interfaces and generics.
- How Angular services and dependency injection work, including
@Injectableandinject(). - What an RxJS
Observableis and howsubscribedelivers values and errors. - How to call
HttpClient.getand handle its result. - How to run unit tests with the Angular CLI, for example with
ng test.
What a service is responsible for
An Angular service usually does one or more of these jobs:
- It holds logic, such as calculations, filtering, validation or state transitions.
- It talks to the outside world, usually over HTTP, and turns responses into the types the app uses.
- It coordinates other services, for example by reading a token from one and attaching it to a call made through another.
Each job suggests a different kind of test. Logic is tested by calling methods and checking results. Outside communication is tested by checking what the service sends and how it reacts to each possible answer. Coordination is tested by replacing the collaborators with stubs and checking how the service uses them.
The guiding question is: if this behavior broke, would a user or another part of the app notice? If yes, a test is justified. If the only thing that would break is the way the code happens to be written, skip the test or reconsider it.
Behavior worth testing
The table below lists what usually deserves a test in a service, and why.
| Behavior | Example | Why it is worth testing |
|---|---|---|
| Business logic | A cart total, a discount rule, a date calculation | Mistakes here produce wrong data without any visible error. |
| The request contract | HTTP method, URL, query parameters, headers, body | The backend depends on this exact shape, and a typo only shows up at runtime. |
| Response handling | Mapping a response body, supplying a default value | The component relies on the type the service returns. |
| Error paths | A 404, a 500, a network failure | Error handling is rarely exercised by hand, so it breaks unnoticed. |
| Retry and timing rules | `retry(2)` on a flaky endpoint | The number of attempts is an observable promise to the user. |
| State changes | A service that stores the logged-in user | Other components read this state. |
| Collaboration | The service asks a token store for a token | A wrong wiring means requests go out unauthenticated. |
Error paths deserve extra attention. Developers usually check the success path in the browser. The failure path is the one nobody tries by hand until production, so it benefits most from an automated test.
What not to test
Some tests look productive but give little protection.
- Framework behavior. Do not test that
HttpClient.getreturns anObservable, or thatinject()finds a service. Angular's own tests cover this. - Private members. A test that reads
cart['prices']breaks when you rename or restructure the field, even though nothing observable changed. - Trivial pass-through code. A method that only forwards its argument to a stub and returns the result has no logic of its own. Testing it only restates the implementation.
- The real backend. A unit test must never depend on a running server. Network speed, data and availability would decide whether the test passes. Chapter by chapter you will replace the HTTP layer so no request leaves the test process.
- Component rendering. How a template shows the data belongs to component tests. A service test should stop at the value the service returns.
A thin HTTP wrapper needs a short note, because it looks trivial but is not. The method getUser(id) below has no logic, yet it has a contract: it must call GET /api/users/{id}. A single test of the method and URL is cheap and catches typos. A second, third and fourth test of the same method add nothing.
Behavior versus implementation
A good test describes what the service promises. A brittle test describes how the service currently works. Compare the two on a service with real logic:
export class CartService {
private prices: number[] = [];
add(price: number): void {
if (price < 0) {
throw new Error('Price must not be negative');
}
this.prices.push(price);
}
total(): number {
return this.prices.reduce((sum, p) => sum + p, 0);
}
}
describe('CartService (brittle)', () => {
it('pushes the price into the prices array', () => {
const cart = new CartService();
cart.add(5);
expect((cart as any).prices).toEqual([5]);
});
});
describe('CartService (behavior)', () => {
it('sums the prices of added items', () => {
const cart = new CartService();
cart.add(5);
cart.add(7);
expect(cart.total()).toBe(12);
});
it('rejects a negative price', () => {
const cart = new CartService();
expect(() => cart.add(-1)).toThrowError('Price must not be negative');
});
it('reports a total of zero for an empty cart', () => {
expect(new CartService().total()).toBe(0);
});
});Suppose you later change prices from an array to a Map keyed by item id. The brittle test fails even though the cart works. The three behavior tests keep passing, because they only use the public methods add and total. This is the practical reason to avoid testing private state.
Notice the edge cases in the second group. The empty cart and the invalid input are the places where logic usually goes wrong. Cover those boundaries before you add more tests for the ordinary case.
Choosing a test style
Not every service needs the same setup. The cheapest test that still proves the behavior is the best one. The flowchart shows the decision.
The three branches map to later chapters:
- A service with no dependencies needs no Angular setup. You create it with
new, asCartServicedid above. - A service with ordinary dependencies uses
TestBedand replaces the collaborators with stubs through providers. - A service that uses
HttpClientusesTestBedwith the testing backend, andHttpTestingControllerlets the test inspect each request and supply the response.
Reaching for TestBed when new would do is a common source of slow, noisy tests. TestBed builds an injector for every test, and that setup is worth paying only when dependency injection is part of what you need.
A worked example: deciding what to cover
Here is the service that the HTTP chapters will test:
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { retry } from 'rxjs/operators';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private readonly http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`);
}
getUserWithRetry(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(retry(2));
}
listUsers(page: number): Observable<User[]> {
return this.http.get<User[]>('/api/users', { params: { page } });
}
}Apply the guiding question to each method:
getUserhas no logic. Its contract is the method and the URL. One test of the request and one test that the response body comes back cover it.getUserWithRetryadds a rule: two retries, so three attempts in total. The rule is the reason the method exists, so test that it succeeds on the third attempt. Also consider that it should fail after the third failure.listUsersbuilds a query string frompage. Test thatpage=2reaches the URL.- Error behavior matters for all three. The service does not catch errors, so the contract is that an
HttpErrorResponsereaches the subscriber. One test per kind of failure (an HTTP status and a network failure) documents this.
That gives a short list of tests, each tied to a promise the service makes. You do not need a test for "the service is created" or "http is defined". If the injector failed to build the service, every other test would fail anyway.
Edge cases and trade-offs
- Over-specifying requests. Asserting on every header of every request makes tests fragile. Assert on the parts the service is responsible for. Leave out headers added by an interceptor, which you test separately.
- Mocking too much. If a test replaces every collaborator with a stub, it can pass while the real wiring is wrong. Stub dependencies that are slow or external. Keep real the small collaborators that are part of the behavior.
- Duplicated coverage. A component test that renders data from a service does not replace a service test. A failure in the component test points to the wrong layer, and it is slower to diagnose.
- Asynchronous assertions that never run. If an assertion sits inside a
subscribecallback and the observable never emits, the test passes without checking anything. Later chapters show how to guard against this. - Tests that mirror the code. If a test contains the same expression as the implementation, it can only fail when you change the code, never when the code is wrong. Prefer concrete expected values such as
12.
Summary of the decision rules
- Test behavior that a user or another part of the app would notice if it broke.
- Test the contract of every request: method, URL, parameters and body.
- Test failure paths, not only success.
- Call only public members.
- Use the lightest setup that proves the behavior:
newfirst,TestBedwhen injection matters. - Leave framework behavior, trivial forwarding and template rendering to other tests.
Exercise
A service method getOrder(id) only calls this.http.get<Order>('/api/orders/' + id) and returns the result. A teammate proposes five tests: (1) the service is created, (2) http is defined, (3) the request uses GET and the right URL, (4) a 404 response reaches the subscriber as an error, (5) a private cache field is empty after construction. Which tests would you keep, and why?
Show answer
Keep tests 3 and 4. Test 3 checks the request contract, which the backend depends on, and a typo in the URL would only show up at runtime. Test 4 checks the error path, which is rarely tried by hand. Drop test 1 because every other test would fail if the service could not be created. Drop test 2 because it checks framework injection, not your logic. Drop test 5 because it reads private state, so it breaks on harmless refactoring and proves nothing a caller can observe.
Exercise
A service has no constructor dependencies and one method that applies a 10 percent discount to orders over 100. Which test style from this chapter fits, and which three inputs would you test first?
Show answer
Create the service with new and call the method directly, with no TestBed. Test the boundary and both sides of it: an amount just under the threshold (such as 99), the threshold itself (100), and an amount above it (such as 200). Each case checks the discount rule at the point where it is most likely to be wrong.