angulartypescripttestingeventemittertestunit

Child Component with EventEmitter test


I have this child component that emit true or false when the style change to a parent component:

export class PruebaComponent implements OnInit, OnChanges {

  @Output() statusEvent = new EventEmitter<boolean>();
  
  getSytle(): string {
     return this.valueStyle;
  }

  private calcStyle(): void {
     this.calcPopUpStyle();
     if (this.isEngReady) {
       this.valueStyle = 'icon-green';
       this.statusEvent .emit(true);
     } else {
       this.valueStyle = 'icon-red';
       this.statusEvent.emit(false);
     }
     this.ref.detectChanges();
   }
} 

I trying to write the test to check that the statusEvent emitted is true when the isEngReady is also true, that I tried this:

describe('PruebaComponent', () => {
   beforeEach(async(() => {
      TestBed.configureTestingModule({
       declarations: [ChatComponent]})
    .compileComponents();
    }));

   it('should emit chat availability to true if the engagement is available', () => {
     spyOn(component.statusEvent, 'emit')
     component.isEngReady = true;
     component.getSytle();
     //expect(component.statusEvent.emit).toHaveBeenCalled();
     expect(component.statusEvent.emit).toHaveBeenCalledWith(true);
   });
});

But I receive this error message: Expected spy emit to have been called with: [ true ] but it was never called.


Solution

  • You should change your spy function from spyOn(component.chatAvailableEvent, 'emit') to spyOn(component.statusEvent, 'emit')

    describe('PruebaComponent', () => {
       beforeEach(async(() => {
          TestBed.configureTestingModule({
           declarations: [ChatComponent]})
        .compileComponents();
        }));
    
       it('should emit chat availability to true if the engagement is available', () => {
         // given
         const statusSpy = spyOn(component.statusEvent, 'emit')
         component.isEngReady = true;
    
         // when
         component.calcStyle() // <-- call here the function or action that trigger this private function.
         // or make it public // I don't recommend that. But it can be.
    
         // expect
         expect(statusSpy).toHaveBeenCalledWith(true);
       });
    });