Sub topic 13
Testing a Feature in Isolation
This chapter assumes you know TypeScript, Angular components and dependency injection, the Angular Router, and the Angular CLI. It also assumes you have read the earlier chapters on route-scoped providers, feature state, and public API barrels. Here you will test one feature without booting the rest of the app.
Why isolation follows from the structure
A feature built with the earlier techniques has clear edges:
- Its store is provided by its route, so it is not in the root injector.
- Its public API is a barrel file, so other code touches only a few symbols.
- Its components are standalone, so each one declares its own imports.
These edges decide what a test must set up. A test for OrdersStore needs HttpClient and nothing else. A test for OrderListComponent needs a store, which can be a fake. Neither test needs the customers feature, the root AppComponent, or the real router configuration.
Isolation means three things here:
- The test creates only what the feature needs.
- Anything outside the feature is replaced with a fake or a stub.
- The test touches only the feature's own files, plus whatever the feature imports through other features' barrels.
Three levels of feature tests
Different parts of a feature need different tests. The table summarizes where each fits.
| Level | Subject | Real parts | Replaced parts |
|---|---|---|---|
| Store | `OrdersStore` | The store | `HttpClient` backend |
| Component | `OrderListComponent` | The component, its template | The store |
| Routed feature | `ORDERS_ROUTES` | Routes, store, components | HTTP backend, other features |
Start at the bottom. Store tests are fast and catch logic errors. Component tests catch template errors. Routed tests catch wiring errors, such as a store that is not provided where a component expects it.
Testing the store
The store from the earlier chapter has no providedIn setting. A test must therefore provide it. Use provideHttpClient together with provideHttpClientTesting so no request leaves the test.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { OrdersStore } from './orders.store';
import { Order } from './order.model';
describe('OrdersStore', () => {
let store: OrdersStore;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
OrdersStore,
provideHttpClient(),
provideHttpClientTesting(),
],
});
store = TestBed.inject(OrdersStore);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => {
http.verify();
});
it('starts empty', () => {
expect(store.orders()).toEqual([]);
expect(store.count()).toBe(0);
});
it('loads orders from the API', () => {
const orders = [{ id: '1' }, { id: '2' }] as unknown as Order[];
store.load();
http.expectOne('/api/orders').flush(orders);
expect(store.orders()).toEqual(orders);
expect(store.count()).toBe(2);
});
});Three details matter here.
providers: [OrdersStore]mirrors what the route does. The test supplies the same provider the route supplies, so the store is created fresh for each test.http.verify()fails the test if a request was made that the test did not expect. This catches accidental extra calls.- Signals are read by calling them.
store.orders()returns the current value, andcountrecomputes when_orderschanges.
Because the store exposes orders through asReadonly(), a test cannot call store.orders.set(...). That is a feature, not an obstacle. To set up state, call a public method such as load() and flush the HTTP response, or add a test-only method if a public one does not exist.
Testing a component with a fake store
A component that injects OrdersStore does not need the real store in its test. Replace it with a small object that has the same shape.
Assume OrderListComponent injects the store, calls load() in its constructor, and renders one list item per order. The fake must provide what the component uses: orders and load.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { OrderListComponent } from './order-list.component';
import { OrdersStore } from '../data-access/orders.store';
import { Order } from '../data-access/order.model';
describe('OrderListComponent', () => {
let fixture: ComponentFixture<OrderListComponent>;
const orders = signal<Order[]>([]);
const load = jasmine.createSpy('load');
beforeEach(async () => {
orders.set([]);
load.calls.reset();
await TestBed.configureTestingModule({
imports: [OrderListComponent],
providers: [
{
provide: OrdersStore,
useValue: { orders: orders.asReadonly(), load },
},
],
}).compileComponents();
fixture = TestBed.createComponent(OrderListComponent);
});
it('asks the store to load orders', () => {
fixture.detectChanges();
expect(load).toHaveBeenCalledTimes(1);
});
it('renders one row per order', () => {
orders.set([{ id: '1' }, { id: '2' }] as unknown as Order[]);
fixture.detectChanges();
const rows = fixture.nativeElement.querySelectorAll('li');
expect(rows.length).toBe(2);
});
});The example uses Jasmine, the default runner in many Angular CLI projects. If your project uses Jest or Vitest, replace jasmine.createSpy with jest.fn() or vi.fn().
The key idea is the provider override. The component calls inject(OrdersStore), and the test container answers with the fake. The component code does not change.
A standalone component lists itself in imports, not declarations. Its own imports (pipes, child components) come along automatically. If the component uses a child component from another feature, you can override it, but prefer to keep the child small and real when it is cheap to render.
Where the fake store stops being useful
Fakes are quick, but they can hide wiring mistakes. If the store's load() signature changes, a fake typed loosely still passes. Two habits reduce this risk.
- Type fakes against the real class, using
PickorPartial, as the warning above says. - Keep at least one test per feature that uses the real store and a fake HTTP backend. The routed-feature test below does this.
Testing the routed feature
A routed test checks what the earlier chapters set up: the route provides the store, the child routes resolve, and the components render. Use RouterTestingHarness, which creates a root component and navigates inside it.
Import ORDERS_ROUTES through the feature's own file. The test is inside the feature, so it does not need the barrel.
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { ORDERS_ROUTES } from './orders.routes';
describe('orders routes', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideRouter(ORDERS_ROUTES),
provideHttpClient(),
provideHttpClientTesting(),
],
});
http = TestBed.inject(HttpTestingController);
});
it('renders the list at the feature root', async () => {
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/');
http.expectOne('/api/orders').flush([{ id: '1' }]);
harness.detectChanges();
const rows = harness.routeNativeElement!.querySelectorAll('li');
expect(rows.length).toBe(1);
});
});Notice what the test does not do. It does not register OrdersStore in providers, because the route's own providers array already does that. If the route forgot to provide the store, this test would fail with a missing-provider error. That is exactly the wiring error you want to catch.
It also mounts ORDERS_ROUTES at the root of the test router, not under /orders. The URL prefix belongs to the app-level routes file, and the feature does not know about it. This is a direct benefit of the lazy-route layout: the feature's tests stay valid if the app renames the prefix.
Dealing with dependencies on other features
Sometimes the feature under test imports something from another feature, such as a customer name lookup. The architecture rules say it does so through that feature's barrel. In a test, you have three options.
- Use the real thing when it is cheap and has no side effects, such as a pure function or a type.
- Provide a fake for the injection token or service, as with the store above.
- Avoid the dependency by passing data in through an
input(), so the component never asks another feature for it.
The third option is the strongest. A component that receives data through inputs is trivial to test: set the input, render, and assert.
For core services such as an auth service, provide a fake in the test and keep the real one out. Core services often hold global state, and sharing it across tests causes failures that depend on test order.
Common errors
NullInjectorError: No provider for OrdersStore. A component test did not supply the store, or a routed test used the component without the route that provides it. Provide a fake or test through the route.- Leaking state between tests. A signal declared outside
beforeEachkeeps its value. Reset it, as the component test above does withorders.set([]). - Forgetting
detectChanges(). A component's template does not render until change detection runs. Callfixture.detectChanges()after changing state. - Unverified HTTP. Without
http.verify(), a feature can send extra requests unnoticed. - Testing through the app root. Importing
AppComponentand navigating the whole app makes every feature test depend on every other feature. Use the harness and the feature's own routes. - Importing from a sibling feature's internals. A test is also subject to the boundary rules. If lint forbids the import in production code, do not allow it in test code either.
Where test files live
Place each spec file next to the file it tests: orders.store.spec.ts beside orders.store.ts. The feature folder then contains everything needed to understand and change it. Do not export spec files or test helpers from the barrel. If several specs in a feature share a fake, put it in a file such as testing/orders-store.fake.ts inside the feature, and keep it out of index.ts.
If another feature needs your fake, that suggests the dependency should be explicit. Expose a testing entry point deliberately, or reconsider whether the two features are too coupled.
Exercise
A route file for the customers feature declares providers: [CustomersStore]. A routed test uses provideRouter(CUSTOMERS_ROUTES) and also lists CustomersStore in the test's providers. The test passes. Later someone removes providers: [CustomersStore] from the route file, and the test still passes, but the app fails at runtime. Why, and how do you fix the test?
Show answer
The test supplies the store itself, so it hides the missing route provider. The test and the app no longer match. Fix the test by removing CustomersStore from the test's providers and letting the route supply it. The test then fails with a missing-provider error when the route's providers entry is removed, which is the failure you want.
Exercise
You write a component test that provides { provide: OrdersStore, useValue: { load } }, but the component template reads store.orders(). What goes wrong, and how can you make the compiler catch it?
Show answer
The template calls orders on an object that has no such member, so rendering throws an error such as "store.orders is not a function". To catch this at compile time, type the fake against the real class, for example const fake: Pick<OrdersStore, 'orders' | 'load'> = { orders: orders.asReadonly(), load }. The compiler then reports the missing orders member.