Sub topic 2
Testing a plain service without TestBed
This chapter assumes you know TypeScript, Angular services and dependency injection, and how to run unit tests with the Angular CLI. Examples use Jasmine-style describe, it and expect. They also work with Jest.
Why skip TestBed
TestBed builds a small Angular module so the injector can create your service. That is useful when the service depends on other providers. It also adds setup code and runs slower.
A service with no dependencies is an ordinary class. You can create it with new and call its methods directly. The test then covers only your own logic.
A first test
CartService keeps a list of prices and adds them up. It has no constructor parameters and does not call inject().
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);
});
});The test follows three steps: create the object, act on it, assert on the result. The service is created inside the it block, so each test gets a fresh instance and no state leaks between tests.
Edge cases are cheap here
Without TestBed, extra cases cost a few lines each. Add one for the empty cart.
it('returns 0 for an empty cart', () => {
expect(new CartService().total()).toBe(0);
});When many tests need the same starting state, create the instance in beforeEach and assign it to a variable declared in the describe block.
Passing dependencies by hand
If a service takes its dependencies through the constructor, you can still skip TestBed. Pass a plain object that has the members the service uses.
export interface Clock {
now(): number;
}
export class SessionService {
constructor(private readonly clock: Clock) {}
isExpired(startedAt: number, ttlMs: number): boolean {
return this.clock.now() - startedAt > ttlMs;
}
}
describe('SessionService', () => {
it('reports a session as expired after the time to live', () => {
const service = new SessionService({ now: () => 10_000 });
expect(service.isExpired(0, 5_000)).toBeTrue();
});
});The stub is a literal object, and the fixed clock makes the result deterministic. toBeTrue() is Jasmine's matcher. In Jest, use toBe(true).
When this approach stops working
Services in current Angular code often get dependencies with inject(), as UserService does with HttpClient. The inject() function only works inside an injection context. Calling new UserService() outside one throws error NG0203. For those services you need TestBed, which the next chapters cover.
Common mistakes
- Sharing one service instance across tests, so one test's state changes another's result.
- Casting a partial stub with
as anyand hiding a missing method until runtime. Typing the stub against an interface, asClockdoes above, lets the compiler catch it. - Switching to
TestBedout of habit for a class that needs none of its features.
Exercise
PriceService declares private readonly config = inject(AppConfig); as a field. A test calls new PriceService() and fails with NG0203. Why does it fail, and what should the test use instead?
Show answer
inject() only works inside an injection context, and a plain new call runs outside one. The test should create the service through TestBed, for example by providing AppConfig (or a stub) and calling TestBed.inject(PriceService). Alternatively, refactor the service to take AppConfig as a constructor parameter, so the test can pass a stub with new.