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

Angular单元测试报错:TypeError: Cannot read property 'filter' of undefined

解决MatRadioGroup封装组件单元测试中的TypeError: Cannot read property 'filter' of undefined问题

看起来你在给封装的MatRadioGroup组件写单元测试时踩了个常见的坑——Jasmine抛出了filter未定义的错误。结合你给出的测试代码片段,我来帮你拆解可能的原因和对应的解决办法:

1. 组件初始化时未对options做空值保护

最常见的原因是:你的组件内部(比如ngOnInit、构造函数或者模板逻辑里)直接对this.options调用了filter方法,但在测试初始化阶段,options还是undefined,直到你在it块里才给它赋值。

修复组件代码:
在组件里使用filter前,先给options加个空值兜底:

// 原来的代码(会报错)
this.selectedOption = this.options.filter(opt => opt.checked)[0];

// 修改后的代码(加空值保护)
this.selectedOption = (this.options || []).filter(opt => opt.checked)[0];

这样即使options还没赋值,也会用空数组来调用filter,避免报错。

2. 测试代码未触发变更检测

你在测试里给component.options赋值后,没有通知Angular更新组件状态,导致组件还是用初始化时的undefined来执行逻辑,进而触发filter报错。

修改测试代码:
在赋值后加上fixture.detectChanges(),触发组件的变更检测:

it('should test the properties of the component', () => { 
  const options = [ 
    { value: 'Option 1', displayValue: 'Option 1' }, 
    { value: 'Option 2', displayValue: 'Option 2', checked: true } 
  ]; 
  component.options = options; 
  component.color = 'primary';
  // 关键:触发变更检测,让组件感知到options的变化
  fixture.detectChanges();

  // 这里可以添加你的断言逻辑,比如:
  const checkedOption = component.options.find(opt => opt.checked);
  expect(checkedOption?.value).toBe('Option 2');
});

3. 依赖服务未正确Mock(如果组件依赖外部数据)

如果你的组件是从某个服务获取options数据,然后对返回值调用filter,那测试时如果没有正确Mock这个服务,服务会返回undefined,同样会触发错误。

Mock依赖服务示例:
假设组件依赖OptionService来获取选项,在测试配置里Mock这个服务:

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [YourCustomRadioComponent],
    imports: [MatRadioModule], // 别忘了导入Material Radio模块
    providers: [
      {
        provide: OptionService,
        useValue: jasmine.createSpyObj('OptionService', ['getOptions'], {
          getOptions: () => [] // 返回空数组或模拟的选项数据
        })
      }
    ]
  }).compileComponents();

  fixture = TestBed.createComponent(YourCustomRadioComponent);
  component = fixture.componentInstance;
});

先从这几个方向排查,基本能解决这个filter未定义的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:15:34