Sub topic 1
What a Service Test Should and Should Not Cover
Prerequisites
Assume TypeScript basics, Angular services and dependency injection, RxJS Observables, and Angular unit-test commands.
Choose the Behavior to Test
A service test checks behavior owned by the service. Test inputs, returned values, state changes, errors, and important calls to dependencies. Do not retest Angular, the HTTP server, or implementation details such as private fields.
A useful test remains valid after a small refactor. For example, test that total() returns the sum, not that the service uses reduce.
Test a Plain Service Without TestBed
TestBed is Angular's test dependency-injection container. A service with no Angular dependencies does not need it. Create the class directly. This makes the test faster and shows exactly what the test controls.
export class CartService {
private prices: number[] = [];
add(price: number): void {
this.prices.push(price);
}
total(): number {
return this.prices.reduce((sum, price) => sum + price, 0);
}
}
describe('CartService', () => {
it('sums added prices', () => {
const cart = new CartService();
cart.add(5);
cart.add(7);
expect(cart.total()).toBe(12);
});
});Create and Inject Services with TestBed
Use TestBed when Angular must construct the service or its dependency graph. Configure providers, then call TestBed.inject.
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UserService],
});
});
it('creates the service', () => {
const service = TestBed.inject(UserService);
expect(service).toBeTruthy();
});If the service uses HttpClient, provide the HTTP testing backend instead of allowing real network requests. The next chapter applies this setup with HttpTestingController.
Replace Dependencies with Stubs
A stub is a small replacement object with controlled behavior. Register it with useValue:
TestBed.configureTestingModule({
providers: [
{ provide: TokenStore, useValue: { token: () => 'stub-token' } },
],
});
const store = TestBed.inject(TokenStore);
expect(store.token()).toBe('stub-token');The stub keeps the test focused on the service. Avoid a stub that duplicates the dependency's entire implementation.
Assert on Observable Results
An Observable is a stream that can emit values later. Subscribe in the test, trigger the service operation, and make assertions after the controlled emission. For HTTP Observables, the test must provide a response before the assertion.
Exercise
When should you instantiate a service with new instead of TestBed?
Show answer
Use new when the service is a plain class with no Angular-managed dependencies. Use TestBed when Angular must construct it or provide its dependencies.