单元测试 Reducer 函数

使用 @ngrx/store 提供的 createReduceron 操作符,可对状态转换逻辑进行隔离测试。
例如:

const myReducer = createReducer(
  initialState,
  on(action, (state) => {
    return { ...state, data: 'test' };
  })
);

测试建议:通过 jest 模拟 action 对象,验证 reducer 返回值是否符合预期
🔗 了解更多 Reducer 测试技巧

效果测试 (Effect)

针对副作用逻辑,可使用 TestBed 模拟 HTTP 请求:

it('should handle success', () => {
  const action = new LoadDataSuccess({ payload: 'test' });
  const expected = { data: 'test' };
  expect(effects.loadData$).toBeObservable(from(action).pipe(map((a) => expected)));
});

📸

NGRX_Effect_Testing

组件与 Store 联动测试

使用 TestBed 创建组件时,需注入 Store 模块:

TestBed.configureTestingModule({
  declarations: [MyComponent],
  providers: [Store, provideMockStore({})]
});

📌 测试要点

  • 使用 store.select() 验证状态订阅
  • 通过 store.dispatch() 模拟用户交互
  • 检查组件 UI 是否响应状态变化

测试工具推荐

🔧 必备工具

高级测试技巧

可尝试

  • 使用 coldhot 模拟 Observable 流程
  • 结合 RouterTestingModule 测试导航相关逻辑
  • 通过 store.overrideSelector 替换特定状态值

📸

Angular_Store_Testing