在测试用例中,需要为组件的输入属性提供值。如果未提供,输入属性将为undefined,因此当组件尝试读取该属性时会出现此错误。以下是一个示例:
组件代码:
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html' }) export class MyComponentComponent { @Input() myInput: string;
getValue(): string { return this.myInput.value; //此处出现TypeError } }
测试用例代码:
describe('MyComponentComponent', () => {
let component: MyComponentComponent;
let fixture: ComponentFixture
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ MyComponentComponent ] }) .compileComponents(); });
beforeEach(() => { fixture = TestBed.createComponent(MyComponentComponent); component = fixture.componentInstance; fixture.detectChanges(); });
it('should get value', () => { component.myInput = {value: 'test'}; //为输入属性myInput提供值 expect(component.getValue()).toEqual('test'); }); });