Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/Jasmine - Do Spies work if invoked on ngOnInit?

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

like image 996
tmcrs123 Avatar asked Sep 11 '25 17:09

tmcrs123


1 Answers

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();
});
like image 109
Amit Chigadani Avatar answered Sep 13 '25 06:09

Amit Chigadani