You need to enable JavaScript to run this app. 测试dxi-item的onValueChanged事件触发时绑定方法未调用问题求助
优惠活动
大模型
产品
解决方案
定价
更多

测试dxi-item的onValueChanged事件触发时绑定方法未调用问题求助

问题定位及修正方案

核心问题1:事件调用方式错误

你从dxForm的items配置中拿到的onValueChanged是直接绑定的组件普通方法,不是Angular的EventEmitter对象,不需要调用.emit(),直接执行该函数即可。

核心问题2:事件参数缺失

DevExtreme的onValueChanged事件触发时会默认传递包含当前值、旧值等信息的事件对象,就算你的方法里没有用到该参数,调用时也建议至少传入空对象避免潜在报错。

额外问题:测试用例描述错误

你的用例描述里写的是验证changeValuePlafond方法调用,和你实际要测试的changeValueCodeCompteurCET不符,属于描述笔误。

修正后的测试代码

it("should call 'changeValueCodeCompteurCET' when the select box value changes", ()=>{
  const spy_changeValueCodeCompteurCET = spyOn(component, "changeValueCodeCompteurCET");
  const dxForm = fixture.debugElement.query(By.css("dx-form"));
  const dxiItem = dxForm.componentInstance.items[0].items[0];
  // 直接调用onValueChanged方法,传入模拟的事件参数
  dxiItem.editorOptions.onValueChanged({ value: '模拟新值', previousValue: '模拟旧值' });
  fixture.detectChanges();
  expect(spy_changeValueCodeCompteurCET).toHaveBeenCalledTimes(1);
});

更稳妥的替代测试方案

如果上面的方法仍存在问题,你可以直接获取页面上的dxSelectBox实例触发事件,更贴近实际用户操作场景:

it("should call 'changeValueCodeCompteurCET' when the select box value changes", ()=>{
  const spy_changeValueCodeCompteurCET = spyOn(component, "changeValueCodeCompteurCET");
  // 直接获取dx-select-box元素
  const selectBox = fixture.debugElement.query(By.css("dx-select-box"));
  // 触发valueChanged事件
  selectBox.componentInstance.onValueChanged.emit({ value: '模拟新值' });
  fixture.detectChanges();
  expect(spy_changeValueCodeCompteurCET).toHaveBeenCalledTimes(1);
});

内容的提问来源于stack exchange,提问作者Nourelayne Salah eddine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 12:24:05