Sub topic 13
Testing a signal store with TestBed
This chapter assumes you know Angular dependency injection, signals, the store pieces from earlier chapters (withState, withComputed, withMethods, rxMethod), and basic Jasmine or Jest syntax.
Why stores are easy to test
A signal store is an injectable service. You don't need a component, a template, or a mocked store. TestBed creates the store, you call its methods, and you read its signals as plain functions. TestBed also resets between tests, so a providedIn: 'root' store starts from its initial state in every test.
Testing methods and computed signals
Call a method, then read the signal. Because patchState updates synchronously, no waiting is needed.
import { TestBed } from '@angular/core/testing';
import { TodosStore } from './todos.store';
describe('TodosStore', () => {
it('filters visible todos', () => {
const store = TestBed.inject(TodosStore);
store.add('Write docs');
store.add('Ship release');
store.toggle(store.todos()[0].id);
store.setFilter('open');
expect(store.visibleTodos().map((t) => t.title)).toEqual(['Ship release']);
expect(store.openCount()).toBe(1);
});
});Todo ids come from Date.now(), so two todos added in the same millisecond can share an id. The test above toggles todos()[0], so it still works. If you toggle by id in your own tests, give the todos distinct ids or inject an id generator.
Setting up state directly
To test a computed signal in a specific state, you don't have to replay every method call. Stores protect their state by default, so patchState(store, ...) on an injected store is rejected. Use unprotected from @ngrx/signals/testing to get write access in a test.
import { TestBed } from '@angular/core/testing';
import { patchState } from '@ngrx/signals';
import { unprotected } from '@ngrx/signals/testing';
import { TodosStore } from './todos.store';
it('counts only open todos', () => {
const store = TestBed.inject(TodosStore);
patchState(unprotected(store), {
todos: [
{ id: 1, title: 'A', done: true },
{ id: 2, title: 'B', done: false },
],
});
expect(store.openCount()).toBe(1);
});Use this for setup only. Make the behavior you are testing go through the store's public methods.
Testing rxMethod with HTTP
UsersStore calls HttpClient, so replace the backend with provideHttpClientTesting(). That store has no providedIn: 'root', so list it in providers.
rxMethod reads a signal argument through an effect. The request does not go out until effects run, so call TestBed.tick() to flush them. On Angular versions before 20, use TestBed.flushEffects().
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 query changes', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
http.expectOne((r) => r.url === '/api/users').flush([]);
store.setQuery('ada');
TestBed.tick();
const req = http.expectOne((r) => r.url === '/api/users');
expect(req.request.params.get('q')).toBe('ada');
expect(store.loading()).toBe(true);
req.flush([{ id: 1, name: 'Ada' }]);
expect(store.users()).toEqual([{ id: 1, name: 'Ada' }]);
expect(store.loading()).toBe(false);
});
it('stores the error message when the request fails', () => {
const store = TestBed.inject(UsersStore);
TestBed.tick();
http.expectOne((r) => r.url === '/api/users').error(new ProgressEvent('error'));
expect(store.loading()).toBe(false);
expect(store.error()).not.toBeNull();
});
});The first TestBed.tick() runs the initial request started by onInit. The afterEach call to http.verify() fails the test if any request was left unmatched.
Common errors
| Symptom | Likely cause |
|---|---|
| `expectOne` finds no request | Effects have not run. Call `TestBed.tick()`. |
| `NullInjectorError` for the store | The store lacks `providedIn: 'root'` and is missing from `providers`. |
| `NullInjectorError` for `HttpClient` | Add `provideHttpClient()` before `provideHttpClientTesting()`. |
| Type error on `patchState(store, ...)` | The state is protected. Wrap the store in `unprotected(...)`. |
| State leaks between tests | You created the store outside TestBed, or you share one instance across tests. |
Exercise
A test for a store that uses rxMethod calls store.setQuery('ada') and then immediately runs http.expectOne('/api/users'), which fails because no request exists. What is missing?
Show answer
The effect behind rxMethod's signal argument has not run yet. Call TestBed.tick() (or TestBed.flushEffects() before Angular 20) after setQuery, then call expectOne. The query string also appears in the URL only if you build it into the URL, so match by req.request.params or use a function matcher.