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

封装mat-radio组件后,单元测试checked属性不生效问题排查

封装Mat-Radio按钮单元测试问题:checked属性无法传递

我在封装mat-radio按钮并编写单元测试时,卡在了「should uniquely select radios by a name」测试用例上。设置封装后的组件的checked输入属性后,该属性无法传递给内部封装的mat-radio-button,导致测试断言不通过。我猜测这是变更检测问题,但仅更新输入属性无法解决,尝试了tick和fixture稳定化操作都无效。

测试代码

it('should uniquely select radios by a name', () => {
  seasonRadioInstances[0].checked = true;
  weatherRadioInstances[1].checked = true; 

  fixture.detectChanges();
// now the mat-radio-button should be updated but is not
  expect(seasonRadioInstances[0].checked).toBe(true);
  expect(seasonRadioInstances[1].checked).toBe(false);
  expect(seasonRadioInstances[2].checked).toBe(false);
  expect(weatherRadioInstances[0].checked).toBe(false);
  expect(weatherRadioInstances[1].checked).toBe(true);
  expect(weatherRadioInstances[2].checked).toBe(false);
}))

测试模板组件代码

@Component({
  template: `
        <my-wrap-radio-button name="season" value="spring">Spring</my-wrap-radio-button>
        <my-wrap-radio-button name="season" value="summer">Summer</my-wrap-radio-button>
        <my-wrap-radio-button name="season" value="autum">Autumn</my-wrap-radio-button>

        <my-wrap-radio-button name="weather" value="warm">Spring</my-wrap-radio-button>
        <my-wrap-radio-button name="weather" value="hot">Summer</my-wrap-radio-button>
        <my-wrap-radio-button name="weather" value="cool">Autumn</my-wrap-radio-button>

        <span id="xyz">Baby Banana</span>
        <span id="abc">A smaller banana</span>
        <my-wrap-radio-button
          name="fruit"
          value="banana"
        >
        </my-wrap-radio-button>
        <my-wrap-radio-button name="fruit" value="raspberry">Raspberry</my-wrap-radio-button>
        <my-wrap-radio-button id="nameless" value="no-name">No name</my-wrap-radio-button>
      `,
})
class StandaloneRadioButtons {
  ariaLabel: string = 'Banana';
  ariaLabelledby: string = 'xyz';
  ariaDescribedby: string = 'abc';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:50:10