I have a reactive form which I have split into smaller components to be able to better manage each form control individually. I'm relying on event emitters to be able to communicate the state of each control to the "parent" component that manages the state of the whole form.
My ngOnInit method for a given component looks like this:
@Output() formReady: EventEmitter<FormControl> = new EventEmitter();
ngOnInit() {
(some other unrelated logic here...)
this.formReady.emit(this.userIdFormControl);
}
The test I'm trying to write for this component is pretty straightforward
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
expect(component.formReady.emit).toHaveBeenCalled();
});
However this is test is failing because the Spy never gets invoked (although if I add a clg statement to ngOnInit I can see it getting printed as many times as expected).
My question is: are Spies able to be invoked on ngOnInit? I can't see why they wouldn't work but you never know!
Thanks in advance,
Tiago
The problem is that, OnInit
is getting called before spy
has been created.
That is because you might be calling fixture.detectChanges()
in beforEach
block. Just remove that and call it in your spec.
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
fixture.detectChanges()
expect(component.formReady.emit).toHaveBeenCalled();
});
Or alternatively you can call ngOnInit()
method again in your spec to see if it is working.
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
component.ngOnInit();
expect(component.formReady.emit).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With