You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 13如何Mock ngRx Store的dispatch与subscribe做单元测试

Angular 13 + NgRx Store 单元测试:同时 Mock dispatch 与数据对象的解决方案

直接手动Mock Store类很容易出现方法缺失的报错,NgRx官方提供了provideMockStore工具,可以完美解决同时Mock dispatch方法和模拟Store数据的需求,以下是具体实现步骤:

1. 导入官方Mock工具

确保导入@ngrx/store/testing中的provideMockStore和MockStore:

import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { Store } from '@ngrx/store';
import { TestBed } from '@angular/core/testing';

2. 在测试模块中配置Mock Store

在configureTestingModule的providers数组中,用provideMockStore替代手动Mock的Store,同时可以传入初始模拟状态:

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [YourComponent], // 替换为你的组件
    providers: [
      // 传入初始状态,对应业务中订阅的Store数据结构
      provideMockStore({ 
        initialState: {
          yourFeatureKey: { // 替换为你的feature key
            data: 'mock initial value'
          }
        }
      })
    ]
  }).compileComponents();

  // 获取MockStore实例,后续用于监控dispatch或更新状态
  store = TestBed.inject(MockStore);
});

3. 测试订阅逻辑

MockStore会自动处理subscribe逻辑,你可以通过验证select调用或更新状态来测试订阅后的业务逻辑:

it('should handle store subscription correctly', () => {
  const component = TestBed.createComponent(YourComponent).componentInstance;
  
  // 监控select方法,验证是否订阅了正确的feature
  const selectSpy = spyOn(store, 'select').and.callThrough();
  expect(selectSpy).toHaveBeenCalledWith('yourFeatureKey');

  // 动态更新Store状态,触发订阅回调
  store.setState({
    yourFeatureKey: {
      data: 'updated mock value'
    }
  });

  // 断言订阅后的业务逻辑是否执行(比如组件属性是否更新)
  expect(component.someProperty).toBe('updated mock value');
});

4. 测试dispatch方法

直接对MockStore实例的dispatch方法做spy监控即可,不会出现“方法不存在”的报错:

it('should dispatch the correct action', () => {
  const component = TestBed.createComponent(YourComponent).componentInstance;
  const dispatchSpy = spyOn(store, 'dispatch');

  // 触发组件中调用dispatch的方法
  component.triggerDispatch();

  // 验证dispatch是否传入了正确的action
  expect(dispatchSpy).toHaveBeenCalledWith({
    type: 'YOUR_ACTION_TYPE',
    payload: 'test payload'
  });
});

关键说明

  • 避免手动用jasmine.createSpyObjMock Store:这种方式容易遗漏dispatch、subscribe等方法,导致测试报错。
  • MockStore完整实现了Store接口的核心方法,能同时满足数据模拟和方法监控的需求。
  • 可以通过store.setState()随时更新模拟状态,覆盖不同场景的订阅逻辑测试。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 10:24:11