Sub topic 2
Testing a plain service without TestBed
This chapter assumes you can write an Angular service, run ng test, and read a Jasmine or Jest describe/it/expect block. Later chapters cover TestBed, so this one covers the case where you don't need it.
What "plain" means here
Many services are ordinary TypeScript classes. They hold state, run calculations, and make decisions. If a class has no dependencies, or its dependencies arrive through the constructor, you can create it with new and test it like any other class.
Angular's dependency injection (DI) is what normally builds services for your application. In a test, DI is optional when you can build the object yourself. Skipping it has three benefits:
- The test runs faster, because there is no Angular testing module to configure and tear down.
- The test is shorter, because the setup is one line.
- The test is more honest. It exercises the class, not the framework's wiring.
A first isolated test
Here is a small service and its test. The class could carry @Injectable({ providedIn: 'root' }) in the application. The decorator makes no difference to this test, because the test never asks Angular to create the class.
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: arrange, act, assert. It creates the object, calls its public methods, and checks the observable result. It never reads prices directly. The test checks that total() returns the right number for the items added, not how the class stores them.
Give every test a fresh instance
Tests that share one instance can pass or fail depending on the order they run in. Create the object in beforeEach so each test starts clean:
describe('CartService', () => {
let cart: CartService;
beforeEach(() => {
cart = new CartService();
});
it('starts with a total of zero', () => {
expect(cart.total()).toBe(0);
});
it('sums the prices of added items', () => {
cart.add(5);
cart.add(7);
expect(cart.total()).toBe(12);
});
it('does not carry items over from another test', () => {
cart.add(1);
expect(cart.total()).toBe(1);
});
});The third test would fail if cart were created once at the top of the file and the earlier tests had already added items to it. With beforeEach, every test gets its own empty cart.
Services with constructor dependencies
A service often needs another object. If that object arrives through the constructor, you can pass a hand-written stand-in. TypeScript's structural typing helps here: any object with the right shape is accepted.
export interface Clock {
now(): number;
}
export class SessionService {
private startedAt: number | null = null;
constructor(private readonly clock: Clock) {}
start(): void {
this.startedAt = this.clock.now();
}
isExpired(maxAgeMs: number): boolean {
if (this.startedAt === null) {
return true;
}
return this.clock.now() - this.startedAt > maxAgeMs;
}
}
describe('SessionService', () => {
let time: number;
let session: SessionService;
beforeEach(() => {
time = 1_000;
session = new SessionService({ now: () => time });
});
it('is expired before it has started', () => {
expect(session.isExpired(60_000)).toBe(true);
});
it('is not expired within the allowed age', () => {
session.start();
time += 30_000;
expect(session.isExpired(60_000)).toBe(false);
});
it('is expired after the allowed age', () => {
session.start();
time += 60_001;
expect(session.isExpired(60_000)).toBe(true);
});
});The stub is the object literal { now: () => time }. The test controls time, so it can move the clock forward without waiting. This removes the main source of flaky tests, which is real time. The test runs the same way every time.
You wrote no framework code to replace the dependency. The next chapters show how to replace dependencies when Angular builds the service, using providers. When you build the service yourself, the constructor argument is the replacement point.
When `new` stops working
Modern Angular services often get their dependencies with inject() in a field initializer, like this:
private readonly http = inject(HttpClient);inject() only works inside an injection context, which is a place where Angular is currently creating something through DI. If you write new UserService() in a test, no such context exists. Angular throws a NG0203 error saying inject() must be called from an injection context.
So the rule is:
- No dependencies, or constructor parameters you can fill yourself: use
new. - Fields that call
inject(): useTestBed, which the next chapter covers.
This is also a design signal. A service with constructor parameters is easy to test in isolation. A service with inject() fields is tidier to write but needs TestBed to test. Neither is wrong. Knowing the cost helps you choose.
What to assert in isolated tests
Test behavior that a caller of the service can see. Good targets for an isolated test include:
- Return values for typical input.
- Edge cases such as empty input, zero, negative numbers, and
null. - State changes that show up through public methods.
- Calls the service makes on a dependency. Check these only when the call is the purpose of the method, for example "saves the draft when the user leaves".
Avoid asserting on private fields, internal helper calls, or the exact order of operations that doesn't matter to callers. Tests like that break when you refactor, even though the behavior is unchanged.
Here are edge cases for the cart:
describe('CartService edge cases', () => {
let cart: CartService;
beforeEach(() => {
cart = new CartService();
});
it('handles prices that are zero', () => {
cart.add(0);
cart.add(4);
expect(cart.total()).toBe(4);
});
it('keeps a running total as items are added', () => {
cart.add(2);
expect(cart.total()).toBe(2);
cart.add(3);
expect(cart.total()).toBe(5);
});
});Calling total() more than once also confirms that total() doesn't change the cart. It is a read, not an update, and a test can pin that down.
Synchronous tests and what comes next
Every test in this chapter is synchronous. The method is called and the result is available on the next line. This is the simplest kind of test, and many service methods fit it.
If a method returns an Observable or a Promise, the result may arrive later, so the assertion has to wait for it. You can still test those services without TestBed when they have no injected dependencies. The chapter on asserting Observable results covers how to wait correctly.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| One shared instance for all tests | State from one test leaks into the next, and results depend on run order | Create the instance in `beforeEach` |
| `new` on a service that uses `inject()` | `NG0203`: `inject()` called outside an injection context | Use `TestBed`, or change to constructor parameters |
| Asserting on private fields | Refactors break tests that describe no real behavior change | Assert on return values and public effects |
| Using `new Date()` or `Date.now()` inside the service | Tests depend on the real clock and can flake | Pass a clock in, as `SessionService` does |
| Testing the stub | Test passes because the stub returns what the test told it to | Assert on the service's own logic |
Summary
You can test a service without TestBed whenever you can build it yourself. Create it in beforeEach, pass stubs through the constructor, and assert on what callers can observe. Switch to TestBed when the service gets its dependencies from inject(), which is where the next chapter begins.
Exercise
A PriceFormatter class has the constructor constructor(private readonly locale: { currency: string }) and a method format(amount: number): string that returns ` ${amount.toFixed(2)} ${this.locale.currency} . Write a test that checks format(3) returns "3.00 EUR", without using TestBed. Then say why new PriceFormatter()` with no argument would not be a valid test setup.
Show answer
Create the instance with a stub and assert on the result:
describe('PriceFormatter', () => {
let formatter: PriceFormatter;
beforeEach(() => {
formatter = new PriceFormatter({ currency: 'EUR' });
});
it('formats an amount with two decimals and the currency', () => {
expect(formatter.format(3)).toBe('3.00 EUR');
});
});
Calling new PriceFormatter() with no argument fails TypeScript's type check, because the constructor requires a locale object. Even if the check were bypassed, this.locale.currency would throw at run time because locale would be undefined. The constructor parameter is where the test supplies the stub.