我有一个具有所需输入的Angular 组件,如果没有提供,我会抛出错误.
export class FormValidationMessageComponent implements OnInit {
@Input() form!: NgForm;
@Input() field!: NgModel;
ngOnInit(): void {
if (typeof this.form === 'undefined') throw new Error(`The 'form' property is not set!`);
if (typeof this.field === 'undefined') throw new Error(`The 'field' property is not set!`);
}
}
我如何测试此行为?当没有提供任何东西时,它确实会在我的测试中抛出一个错误,但是我如何在我的expect
中捕获这个错误呢?
let component: FormValidationMessageComponent;
let fixture: ComponentFixture<FormValidationMessageComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormValidationMessageComponent],
});
fixture = TestBed.createComponent(FormValidationMessageComponent);
component = fixture.componentInstance;
});
it('should throw an error when the `form` input is not provided', () => {
const onInitSpy = spyOn(component, 'ngOnInit');
component.field = {} as NgModel;
fixture.detectChanges(); //Triggers ngOnInit()
expect(onInitSpy).toThrow();
});
上述测试仍会抛出错误,并且测试失败
Error: The 'form' property is not set!
我也试了expect(component).toThrow();
次,结果都是一样的