I have an Angular component with required inputs, and I throw an error if they are not provided.
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!`);
}
}
How can I test this behavior? It does throw an error in my test when nothing is provided, but how do I capture this in my 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();
});
The above test still throws an error and the test fails
Error: The 'form' property is not set!
I have also tried expect(component).toThrow(); with the same results