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

NgRx MockStore单元测试报错:dispatch调用参数不匹配求助

问题排查与修复

核心问题是组件实例的this.item属性在测试中未被赋值,调用addCart()时this.item为undefined,最终导致dispatch的Action里allItem为undefined。

直接修复方案

在测试用例中,创建完item对象后,将其赋值给组件的item属性:

it('should dispatch the item',  () => {
    const storeSpy = spyOn(store, 'dispatch').and.callThrough();

    const item: Item = {
      id: 1,
      name: 'milk', // 原代码此处缺少引号,需补上避免变量未定义报错
      price: 5
    };

    // 关键步骤:将测试用的item赋值给组件实例的item属性
    component.item = item;

    component.addCart();
    expect(storeSpy).toHaveBeenCalledWith(
       retrieveItemList({allItem: item })
    );
});

其他场景的补充排查

如果组件的item是通过@Input()接收的,需确保测试中正确设置输入属性:

// 若使用Fixture
fixture.componentInstance.item = item;
fixture.detectChanges();

如果item是从NgRx Store通过Selector获取的,需模拟Selector返回值:

// 假设存在selectItem这个Selector
store.overrideSelector(selectItem, item);
store.refreshState(); // 刷新状态让组件订阅到更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:30:49