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

Angular中Mat Select默认值与禁用场景的单元测试编写需求

Angular Mat Select 单元测试实现

先修正原TS代码的语法问题

原代码里有几处语法错误,先改了才能保证逻辑正常运行:

  • 箭头函数要使用=>,而非->
  • 判断相等要用===,别写成赋值的=
  • 引号要统一,避免单双引号混用

修正后的核心逻辑代码:

this.example = [{name:'abc'},{name:'xyz'}];
const defaultOption = this.example.filter((x) => x.name === 'abc');
 
if (defaultOption.length > 0) {
  const name = defaultOption.find((x) => x.name).name;
  this.myTestForm.controls['test'].setValue(name);
  const defaultCount = 2;
  if(this.example.length < defaultCount && defaultOption.some((x) => x.name === "abc")){
    this.myTestForm.controls['test'].disable();
  } else {
    this.myTestForm.controls['test'].enable();
  }
}

针对性单元测试用例

用Angular标配的Jasmine+Karma编写测试,覆盖你需要的两个核心场景:

场景1:下拉框包含'abc'和其他选项时,默认值设为'abc'

it('should set "abc" as default value when options include "abc" and others', () => {
  // 给组件的选项数组赋值
  component.example = [{name: 'abc'}, {name: 'xyz'}];
  // 触发变更检测,让逻辑执行
  fixture.detectChanges();

  // 验证表单值是否正确
  expect(component.myTestForm.get('test').value).toBe('abc');
  // 验证控件处于启用状态
  expect(component.myTestForm.get('test').enabled).toBeTrue();
});

场景2:下拉框仅含'abc'一个选项时,默认值为'abc'且控件禁用

it('should set "abc" as default and disable the select when only "abc" exists', () => {
  component.example = [{name: 'abc'}];
  fixture.detectChanges();

  // 校验默认值
  expect(component.myTestForm.get('test').value).toBe('abc');
  // 校验控件已禁用
  expect(component.myTestForm.get('test').disabled).toBeTrue();
});

额外补充:无'abc'选项的边界测试(可选)

it('should not set default value and keep control enabled when no "abc" option', () => {
  component.example = [{name: 'xyz'}, {name: '123'}];
  fixture.detectChanges();

  // 这里根据你的表单初始值调整,比如初始为null
  expect(component.myTestForm.get('test').value).toBeNull();
  expect(component.myTestForm.get('test').enabled).toBeTrue();
});

测试注意点

  • 测试模块要配置好依赖:ReactiveFormsModule、MatSelectModule、MatFormFieldModule这些都得加在TestBed.configureTestingModule里
  • 如果你的逻辑是在ngOnInit里执行的,要么在组件实例化前就给example赋值,要么改完example后手动调用component.ngOnInit()再触发变更检测
  • 必须调用fixture.detectChanges()触发变更检测,确保组件逻辑执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:00:37