Sub topic 13
Testing a signal store with TestBed
A signal store is an injectable service that exposes signals and methods. You can test it like any other Angular service: create it through TestBed, call its methods, and assert on the signals it exposes. This chapter covers what to test, how to set up the injector, and how to handle the cases that need extra care: protected state, effects, HTTP calls through rxMethod, and reusable features.
You should already know Angular dependency injection, signals (signal, computed, effect), and basic unit testing with describe, it and expect. The examples use Jasmine-style matchers, which also work in Jest and Vitest. Earlier chapters defined TodosStore, UsersStore and withRequestStatus, and the tests below use them.
What to test
A store has three kinds of public surface. Each one needs a different kind of test.
| Surface | What to assert | Typical setup |
|---|---|---|
| State signals | Value after a method call | `TestBed.inject` |
| Computed signals | Derived value after state changes | `TestBed.inject` |
| Methods with side effects | HTTP requests, loading and error flags | HTTP testing providers |
Test behavior through the public API: call a method, then read a signal. Do not assert on how patchState was called. Such tests break when you refactor, even if behavior is unchanged.
Testing a root-provided store
TodosStore uses providedIn: 'root', so TestBed.inject creates it without any configuration.
import { TestBed } from '@angular/core/testing';
import { TodosStore } from './todos.store';
describe('TodosStore', () => {
it('starts empty with the "all" filter', () => {
const store = TestBed.inject(TodosStore);
expect(store.todos()).toEqual([]);
expect(store.filter()).toBe('all');
expect(store.openCount()).toBe(0);
});
it('tracks the number of open todos', () => {
const store = TestBed.inject(TodosStore);
store.add('Write docs');
expect(store.openCount()).toBe(1);
store.toggle(store.todos()[0].id);
expect(store.openCount()).toBe(0);
});
it('shows only matching todos for the selected filter', () => {
const store = TestBed.inject(TodosStore);
store.add('Write docs');
store.toggle(store.todos()[0].id);
store.setFilter('open');
expect(store.visibleTodos()).toEqual([]);
store.setFilter('done');
expect(store.visibleTodos().length).toBe(1);
});
});TestBed resets between tests, so every test gets a fresh store with initial state. You do not need to clean up manually.
Computed signals read synchronously. You do not need to wait for change detection before asserting on openCount().
Immutability checks
A store that mutates state in place can break computed signals, because a signal only notifies when its value changes by reference. A useful test keeps the old array and checks that it was not modified:
it('does not mutate the previous todos array', () => {
const store = TestBed.inject(TodosStore);
store.add('One');
const before = store.todos();
store.add('Two');
expect(before.length).toBe(1);
expect(store.todos()).not.toBe(before);
});A gotcha with generated ids
TodosStore.add creates ids with Date.now(). Two add calls in the same millisecond produce the same id, and toggle then flips both todos. In a test this shows up as a flaky failure. Either add todos in separate tests, or fix the clock:
it('toggles only the targeted todo', () => {
let now = 1000;
spyOn(Date, 'now').and.callFake(() => now++);
const store = TestBed.inject(TodosStore);
store.add('A');
store.add('B');
store.toggle(store.todos()[0].id);
expect(store.todos().map((t) => t.done)).toEqual([true, false]);
});In Jest or Vitest, use jest.spyOn(Date, 'now') or vi.spyOn(Date, 'now') instead. In production code, a counter or crypto.randomUUID() avoids the problem entirely.
Stores that are not provided in root
A store declared without providedIn: 'root', like UsersStore, is not registered anywhere. TestBed.inject(UsersStore) fails with a "No provider" error. List the store in providers:
TestBed.configureTestingModule({ providers: [UsersStore] });This matches how a component provides the store in its providers array. See the chapter on scoping for that setup. Each TestBed injector creates one instance, which is the same lifetime a component-level store has.
Setting state directly
By default, signalStore protects its state. Outside the store, patchState(store, ...) does not compile, so a test cannot jump straight to an interesting state. You have two options.
The first is to reach the state through public methods. This is the most realistic option, and it works well for small setups.
The second is unprotected from @ngrx/signals/testing. It returns the same store with writable state:
import { TestBed } from '@angular/core/testing';
import { patchState } from '@ngrx/signals';
import { unprotected } from '@ngrx/signals/testing';
import { TodosStore } from './todos.store';
it('counts open todos from a prepared state', () => {
const store = TestBed.inject(TodosStore);
patchState(unprotected(store), {
todos: [
{ id: 1, title: 'A', done: false },
{ id: 2, title: 'B', done: true },
],
});
expect(store.openCount()).toBe(1);
});unprotected is available in recent NgRx versions (v19 and later). Use it only in tests. If your project does not have it, set protectedState: false in the store options for tests only, or build up state through methods.
Testing rxMethod and HTTP calls
UsersStore calls http.get inside an rxMethod. To test it, replace the real HTTP backend with HttpTestingController. Provide provideHttpClient() first and provideHttpClientTesting() after it.
Two details matter:
rxMethodgiven a signal reruns through an effect. The effect runs only when Angular flushes effects, so callTestBed.tick()after creating the store and after each state change that should trigger a request. Older Angular versions useTestBed.flushEffects()for the same job.onInitruns when the store is first created, so the first request is pending as soon as you inject the store and tick.
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { UsersStore } from './users.store';
describe('UsersStore', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UsersStore, provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('loads users when the store starts', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
const req = http.expectOne((r) => r.url === '/api/users');
expect(req.request.params.get('q')).toBe('');
expect(store.loading()).toBe(true);
req.flush([{ id: 1, name: 'Ada' }]);
expect(store.users()).toEqual([{ id: 1, name: 'Ada' }]);
expect(store.loading()).toBe(false);
expect(store.error()).toBeNull();
});
it('requests again when the query changes', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
http.expectOne('/api/users?q=').flush([]);
store.setQuery('ada');
TestBed.tick();
const req = http.expectOne('/api/users?q=ada');
req.flush([{ id: 1, name: 'Ada' }]);
expect(store.users().length).toBe(1);
});
it('stores the error message when the request fails', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
http
.expectOne((r) => r.url === '/api/users')
.flush('boom', { status: 500, statusText: 'Server Error' });
expect(store.loading()).toBe(false);
expect(store.error()).toContain('500');
});
it('cancels the previous request when the query changes quickly', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
const first = http.expectOne('/api/users?q=');
store.setQuery('a');
TestBed.tick();
expect(first.cancelled).toBe(true);
http.expectOne('/api/users?q=a').flush([]);
});
});The afterEach call to http.verify() fails the test if a request was made and never handled. This catches missing expectOne calls and accidental extra requests.
The last test checks the switchMap behavior. If someone changes it to mergeMap, the first request is no longer cancelled and the test fails.
Prefer the string form of expectOne when the whole URL with parameters is what you care about. Use the predicate form when you want to inspect parameters separately.
Testing a custom feature
A feature built with signalStoreFeature is a function, so test it in a small store defined inside the test file. This checks the feature alone, without the rest of a real store.
import { TestBed } from '@angular/core/testing';
import { patchState, signalStore, withMethods } from '@ngrx/signals';
import { unprotected } from '@ngrx/signals/testing';
import { withRequestStatus } from './with-request-status';
describe('withRequestStatus', () => {
const TestStore = signalStore(
{ providedIn: 'root' },
withRequestStatus(),
withMethods((store) => ({
fail(message: string): void {
patchState(store, { requestStatus: { error: message } });
},
})),
);
it('derives isPending and error from requestStatus', () => {
const store = TestBed.inject(TestStore);
expect(store.isPending()).toBe(false);
expect(store.error()).toBeNull();
patchState(unprotected(store), { requestStatus: 'pending' });
expect(store.isPending()).toBe(true);
store.fail('Nope');
expect(store.isPending()).toBe(false);
expect(store.error()).toBe('Nope');
});
});Test each feature once in isolation. Then the stores that use it only need tests for their own behavior.
Testing components that use a store
When a component injects a store, you have two choices:
- Use the real store and assert on the rendered output. This tests the component and store together and catches wiring errors.
- Replace the store with a stub when you want to isolate the component, or when the real store would call the network.
A stub needs the same signal and method shape that the component uses:
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { TodosComponent } from './todos.component';
import { TodosStore } from './todos.store';
it('renders the open count from the store', () => {
const stub = {
openCount: signal(3),
visibleTodos: signal([]),
toggle: jasmine.createSpy('toggle'),
};
TestBed.configureTestingModule({
imports: [TodosComponent],
providers: [{ provide: TodosStore, useValue: stub }],
});
const fixture = TestBed.createComponent(TodosComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('3 open');
});A component that lists the store in its own providers array ignores a root-level override. In that case, use TestBed.overrideComponent to replace the provider on the component.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullInjectorError: No provider for ...Store` | Store has no `providedIn: 'root'` | Add the store to `providers` |
| Type error on `patchState(store, ...)` in a test | Protected state | Use `unprotected(store)` or a store method |
| `expectOne` finds no request | Effects were not flushed | Call `TestBed.tick()` |
| `http.verify()` reports open requests | A request was never flushed | Handle every request with `expectOne` |
| State leaks between tests | Store instance shared outside `TestBed` | Create the store inside each test or `beforeEach` |
| Flaky toggle or remove tests | Duplicate ids from `Date.now()` | Fix the clock or use unique ids |
Exercise
A store test calls store.setQuery('ada'), then immediately calls http.expectOne('/api/users?q=ada'), and the test fails with "Expected one matching request, found none". The store uses an rxMethod that was passed the query signal. What is missing, and why?
Show answer
The test must call TestBed.tick() between setQuery and expectOne. An rxMethod that receives a signal watches it through an effect, and effects run only when Angular flushes them. Until then, the new query has not reached the switchMap, so no request has been made. After TestBed.tick(), the effect runs, the request is sent, and expectOne finds it.