Sub topic 1
What a service test should and should not cover
A service test checks the behavior your service promises to the rest of the app. It does not check how Angular, RxJS or the browser work. This chapter helps you decide what belongs in a service test before you write one.
Prerequisites
This chapter assumes you know:
- TypeScript basics.
- Angular services and dependency injection.
- RxJS Observables and
subscribe. - Angular
HttpClientbasics. - How to run unit tests with the Angular CLI.
What a service owns
A service usually has three jobs. It holds state, it computes values, and it talks to the outside world, often through HttpClient. Each job has behavior that belongs to your code, and a test should pin that behavior down.
Take the UserService from this tutorial. It has three methods:
getUser(id)requests/api/users/{id}and returns theUserit receives.getUserWithRetry(id)makes the same request, but tries again up to twice after a failure.listUsers(page)requests/api/userswith apagequery parameter.
The promises a caller relies on are the URL, the method, the parameters, the shape of the returned data, and what happens on failure. Those are worth testing.
Worth testing
- Return values and state changes. Given these inputs, the service returns or stores this result.
- The outgoing request. The HTTP method, the URL, query parameters, headers and body.
- Response handling. Whether the service passes the body through, maps it, or caches it.
- Failure paths. What the subscriber sees on a 404, a 500 or a network error.
- Retry and fallback rules. How many attempts happen, and what the final outcome is.
- Branches with real logic. Conditions, defaults and edge cases such as an empty list.
Not worth testing
- Framework behavior. Do not test that
HttpClientserializes parameters or that dependency injection works. Angular's own tests cover that. - Implementation details. Do not assert that a private method ran, or that
http.getwas called with a particular argument list when you could assert the request itself. These tests break when you refactor, even if the behavior is unchanged. - Trivial pass-throughs. A getter that returns a field has no logic to protect.
- The real backend. A unit test must never reach the network. It would be slow, flaky, and would test the server instead of your service.
Choosing the lightest setup
The setup should match the dependencies. A service with no dependencies can be created with new and needs no TestBed:
export class CartService {
private prices: number[] = [];
add(price: number): void {
this.prices.push(price);
}
total(): number {
return this.prices.reduce((sum, p) => sum + p, 0);
}
}
describe('CartService', () => {
it('sums the prices of added items', () => {
const cart = new CartService();
cart.add(5);
cart.add(7);
expect(cart.total()).toBe(12);
});
});This test states an input and an expected output. It would survive a rewrite of total() that used a loop instead of reduce.
Services that inject other services or HttpClient need TestBed, so Angular can provide stubs or a fake HTTP backend. The next chapters cover that setup.
Exercise
A teammate writes a test for UserService.getUser that only checks that HttpClient.get was called once. Name one behavior the test misses and one reason it is brittle.
Show answer
It misses the URL, the HTTP method and the returned body, so the service could request the wrong endpoint and still pass. It is brittle because it is tied to how the service calls HttpClient. If you refactor to a different but equivalent call, the test fails even though callers see no change.
Exercise
Which of these needs TestBed: a pure CartService with no dependencies, or a UserService that injects HttpClient?
Show answer
UserService needs TestBed so that Angular can provide HttpClient and a fake HTTP backend. CartService can be created with new.