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

Angular 5单元测试报错:TypeError: Cannot set property 'search' of undefined

解决Angular 5单元测试中filter相关的TypeError问题

你遇到的问题核心在于组件的filter输入属性在测试初始化阶段未被正确实例化,导致访问它的search属性时抛出错误。我们一步步拆解和解决:

问题根源分析

你的组件里filter是@Input()属性,在测试代码中,你直接尝试访问component.filter.search,但此时component.filter还没有被赋值,处于undefined状态:

  • 第一次报错Cannot read property 'search' of null:说明filter初始为null,尝试读取其search属性失败
  • 第二次尝试设置component.filter.search = 'test'时,因为filter本身是undefined,所以报错Cannot set property 'search' of undefined

解决方案

你需要在测试中先实例化filter对象,再访问或修改它的search属性,具体操作如下:

修改后的测试代码示例

import { FormsModule } from '@angular/forms';
import { async, ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { CheckboxModule } from '@kehe-dev/connect-common-web-components';
import { ItemBrandFilterComponent } from './item-brand-filter.component';
import { ItemBrandSearchResponseService } from '../../services/item-brand-search-response.service';
import { ItemFilter } from '../../models/item-filter';

describe('Component: ItemBrandFilterComponent', () => {
  let component: ItemBrandFilterComponent;
  let fixture: ComponentFixture<ItemBrandFilterComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ItemBrandFilterComponent ],
      imports: [ CheckboxModule, FormsModule, HttpClientTestingModule, RouterTestingModule ],
      providers: [ ItemBrandSearchResponseService ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ItemBrandFilterComponent);
    component = fixture.componentInstance;
    
    // 关键步骤:先实例化filter对象,再设置search属性
    component.filter = new ItemFilter(); 
    // 也可以用类型断言的字面量简化:component.filter = { search: 'test' } as ItemFilter
    component.filter.search = 'test';
    
    fixture.detectChanges();
  });

  it('should create', inject([ItemBrandSearchResponseService], (service: ItemBrandSearchResponseService) => {
    expect(component).toBeTruthy();
  }));
});

额外说明

  • 如果ItemFilter类有必填的构造参数,你需要根据模型定义传入对应的值,比如new ItemFilter('initial-value')
  • 使用字面量+类型断言的方式,适合仅需要模拟部分属性的场景,能快速满足测试需求

这样修改后,filter对象被正确初始化,你就能正常访问和修改它的search属性,避免之前的TypeError错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:48:51