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

Ember.js子类调用父类方法的Sinon单元测试断言问题

解决Ember组件父类方法Stub与断言问题

你的测试代码存在两个关键问题:

  • 父类默认将isValid设为false,导致onPress里的条件分支不会执行,togglePropertyInParent()根本不会被调用;
  • 你直接断言this.togglePropertyInParent,但此处的this并非组件实例,且未对父类方法做Stub处理。

下面是两种可行的修正方案:

方案一:Stub组件实例方法(推荐,聚焦当前组件测试)

test('The toggler gets called if the key is pressed', function(assert) {
  // 创建组件实例
  const component = this.owner.factoryFor('component:child-component').create();
  // 设置isValid为true,触发条件分支
  component.set('isValid', true);
  // Stub组件实例上的父类方法
  const toggleStub = sinon.stub(component, 'togglePropertyInParent');

  // 触发组件动作
  component.send('onPress');

  // 断言方法被调用一次
  sinon.assert.calledOnce(toggleStub);
  // 恢复Stub,避免影响其他测试
  toggleStub.restore();
});

方案二:Stub父类原型方法(适合批量Stub父类方法场景)

import Parent from 'path/to/Parent'; // 替换为你的Parent组件实际路径

test('The toggler gets called if the key is pressed', function(assert) {
  // Stub父类原型上的目标方法
  const parentToggleStub = sinon.stub(Parent.prototype, 'togglePropertyInParent');
  
  // 创建组件实例时直接传入isValid为true
  const component = this.owner.factoryFor('component:child-component').create({ isValid: true });

  // 触发组件动作
  component.send('onPress');

  // 断言方法被调用一次
  sinon.assert.calledOnce(parentToggleStub);
  // 恢复Stub
  parentToggleStub.restore();
});

注意事项

  • 必须确保isValid为true,否则条件分支不执行,断言必然失败;
  • 所有Stub操作完成后务必调用restore(),防止Stub污染后续测试用例;
  • 若你使用的Ember版本较新,也可使用this.owner.lookup('component:child-component')替代factoryFor.create,功能一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:50:30