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
相关产品推荐
相关产品推荐

