NgRx SignalStore 测试指南:从基础到高级实践
前言
在 Angular 状态管理领域,NgRx 一直是最受欢迎的解决方案之一。随着 Angular 16 引入 Signals 特性,NgRx 团队推出了 SignalStore 这一全新状态管理方案,它充分利用了 Signals 的响应式特性。本文将全面介绍如何为 SignalStore 编写有效的测试用例,涵盖从基础到高级的各种测试场景。
SignalStore 测试基础
无依赖测试
对于不依赖外部服务的简单 SignalStore,我们可以直接创建实例进行测试:
import { signalStore, withState } from '@ngrx/signals';
const CounterStore = signalStore(
withState({ count: 0 })
);
describe('CounterStore', () => {
it('should initialize with count 0', () => {
const store = new CounterStore();
expect(store.count()).toBe(0);
});
});
这种测试方式简单直接,适合验证 Store 的初始状态和基础功能。
使用 TestBed 测试
大多数情况下,SignalStore 会依赖其他服务,这时我们需要使用 Angular 的测试工具 TestBed:
import { TestBed } from '@angular/core/testing';
import { signalStore, withState, withMethods } from '@ngrx/signals';
const AuthStore = signalStore(
withState({ user: null }),
withMethods(({ $user }) => ({
login: (user) => patchState($user, user)
}))
);
describe('AuthStore', () => {
let store: AuthStore;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthStore]
});
store = TestBed.inject(AuthStore);
});
it('should update user on login', () => {
const testUser = { name: 'Test User' };
store.login(testUser);
expect(store.user()).toEqual(testUser);
});
});
依赖注入与模拟
模拟服务依赖
当 Store 依赖外部服务时,我们需要模拟这些服务:
import { inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const DataStore = signalStore(
withState({ data: null }),
withMethods((store, http = inject(HttpClient)) => ({
loadData: () => {
http.get('/api/data').subscribe(data => {
patchState(store, { data });
});
}
}))
);
describe('DataStore', () => {
let store: DataStore;
let httpMock: jest.Mocked<HttpClient>;
beforeEach(() => {
httpMock = {
get: jest.fn()
} as any;
TestBed.configureTestingModule({
providers: [
DataStore,
{ provide: HttpClient, useValue: httpMock }
]
});
store = TestBed.inject(DataStore);
});
it('should load data from API', () => {
const testData = { id: 1 };
httpMock.get.mockReturnValue(of(testData));
store.loadData();
expect(httpMock.get).toHaveBeenCalledWith('/api/data');
expect(store.data()).toEqual(testData);
});
});
测试 rxMethod
rxMethod 是 SignalStore 中处理异步操作的重要特性,测试时需要特别注意:
import { rxMethod } from '@ngrx/signals';
import { of } from 'rxjs';
const SearchStore = signalStore(
withState({ results: [] }),
withMethods((store) => ({
search: rxMethod<string>((query$) => {
return query$.pipe(
switchMap(query =>
query ? http.get(`/search?q=${query}`) : of([])
),
tap(results => patchState(store, { results }))
);
}))
})
);
describe('SearchStore', () => {
let store: SearchStore;
let httpMock: jest.Mocked<HttpClient>;
beforeEach(() => {
httpMock = {
get: jest.fn()
} as any;
TestBed.configureTestingModule({
providers: [
SearchStore,
{ provide: HttpClient, useValue: httpMock }
]
});
store = TestBed.inject(SearchStore);
});
it('should perform search', () => {
const testResults = [{ id: 1 }];
httpMock.get.mockReturnValue(of(testResults));
store.search('test');
expect(httpMock.get).toHaveBeenCalledWith('/search?q=test');
expect(store.results()).toEqual(testResults);
});
it('should handle empty query', () => {
store.search('');
expect(store.results()).toEqual([]);
expect(httpMock.get).not.toHaveBeenCalled();
});
});
高级测试技巧
测试自定义 Store 特性
对于复杂的自定义 Store 特性,我们可以单独测试其行为:
function withLogger() {
return (store: SignalStore) => {
const actions = new Subject<string>();
return {
...store,
logAction: (action: string) => actions.next(action),
actions$: actions.asObservable()
};
};
}
describe('withLogger', () => {
it('should log actions', () => {
const TestStore = signalStore(withLogger());
const store = new TestStore();
const spy = jest.fn();
store.actions$.subscribe(spy);
store.logAction('test');
expect(spy).toHaveBeenCalledWith('test');
});
});
测试计算属性
计算属性(computed)是 SignalStore 的重要特性,测试时需要注意其惰性求值特性:
const CartStore = signalStore(
withState({ items: [] }),
withComputed(({ items }) => ({
total: computed(() =>
items().reduce((sum, item) => sum + item.price, 0)
)
}))
);
describe('CartStore', () => {
it('should calculate total', () => {
const store = new CartStore();
expect(store.total()).toBe(0);
patchState(store, {
items: [{ price: 10 }, { price: 20 }]
});
// 必须访问计算属性才会触发计算
expect(store.total()).toBe(30);
});
});
测试最佳实践
-
隔离测试:尽量将业务逻辑与状态管理分离,使得 Store 主要处理状态变更,业务逻辑由服务处理。
-
小范围测试:每个测试用例只验证一个特定行为,保持测试简洁明确。
-
状态验证:测试 Store 时,重点验证状态变更是否符合预期,而不是实现细节。
-
异步处理:对于涉及异步操作的测试,确保使用适当的工具(如 fakeAsync 或 waitForAsync)处理异步行为。
-
类型安全:充分利用 TypeScript 的类型系统,确保测试代码也能享受类型检查的好处。
结语
SignalStore 作为 NgRx 的新成员,为 Angular 应用状态管理带来了更简洁、更响应式的解决方案。通过本文介绍的各种测试方法,开发者可以确保 SignalStore 在各种场景下都能可靠工作。随着 SignalStore 的不断演进,测试方法也将持续完善,建议开发者关注 NgRx 官方文档获取最新测试实践。
PaddleOCR-VLPaddleOCR-VL 是一款顶尖且资源高效的文档解析专用模型。其核心组件为 PaddleOCR-VL-0.9B,这是一款精简却功能强大的视觉语言模型(VLM)。该模型融合了 NaViT 风格的动态分辨率视觉编码器与 ERNIE-4.5-0.3B 语言模型,可实现精准的元素识别。Python00- DDeepSeek-OCRDeepSeek-OCR是一款以大语言模型为核心的开源工具,从LLM视角出发,探索视觉文本压缩的极限。Python00
MiniCPM-V-4_5MiniCPM-V 4.5 是 MiniCPM-V 系列中最新且功能最强的模型。该模型基于 Qwen3-8B 和 SigLIP2-400M 构建,总参数量为 80 亿。与之前的 MiniCPM-V 和 MiniCPM-o 模型相比,它在性能上有显著提升,并引入了新的实用功能Python00
HunyuanWorld-Mirror混元3D世界重建模型,支持多模态先验注入和多任务统一输出Python00
MiniMax-M2MiniMax-M2是MiniMaxAI开源的高效MoE模型,2300亿总参数中仅激活100亿,却在编码和智能体任务上表现卓越。它支持多文件编辑、终端操作和复杂工具链调用Jinja00
Spark-Scilit-X1-13B科大讯飞Spark Scilit-X1-13B基于最新一代科大讯飞基础模型,并针对源自科学文献的多项核心任务进行了训练。作为一款专为学术研究场景打造的大型语言模型,它在论文辅助阅读、学术翻译、英语润色和评论生成等方面均表现出色,旨在为研究人员、教师和学生提供高效、精准的智能辅助。Python00
GOT-OCR-2.0-hf阶跃星辰StepFun推出的GOT-OCR-2.0-hf是一款强大的多语言OCR开源模型,支持从普通文档到复杂场景的文字识别。它能精准处理表格、图表、数学公式、几何图形甚至乐谱等特殊内容,输出结果可通过第三方工具渲染成多种格式。模型支持1024×1024高分辨率输入,具备多页批量处理、动态分块识别和交互式区域选择等创新功能,用户可通过坐标或颜色指定识别区域。基于Apache 2.0协议开源,提供Hugging Face演示和完整代码,适用于学术研究到工业应用的广泛场景,为OCR领域带来突破性解决方案。00- HHowToCook程序员在家做饭方法指南。Programmer's guide about how to cook at home (Chinese only).Dockerfile014
Spark-Chemistry-X1-13B科大讯飞星火化学-X1-13B (iFLYTEK Spark Chemistry-X1-13B) 是一款专为化学领域优化的大语言模型。它由星火-X1 (Spark-X1) 基础模型微调而来,在化学知识问答、分子性质预测、化学名称转换和科学推理方面展现出强大的能力,同时保持了强大的通用语言理解与生成能力。Python00- PpathwayPathway is an open framework for high-throughput and low-latency real-time data processing.Python00