Any way to test EventEmitter in Angular2?

tallkid24 picture tallkid24 · Feb 10, 2016 · Viewed 94.1k times · Source

I have a component that uses an EventEmitter and the EventEmitter is used when someone on the page is clicked. Is there any way that I can observe the EventEmitter during a unit test, and use TestComponentBuilder to click the element that triggers the EventEmitter.next() method and see what was sent?

Answer

cexbrayat picture cexbrayat · Feb 10, 2016

Your test could be:

it('should emit on click', () => {
   const fixture = TestBed.createComponent(MyComponent);
   // spy on event emitter
   const component = fixture.componentInstance; 
   spyOn(component.myEventEmitter, 'emit');

   // trigger the click
   const nativeElement = fixture.nativeElement;
   const button = nativeElement.querySelector('button');
   button.dispatchEvent(new Event('click'));

   fixture.detectChanges();

   expect(component.myEventEmitter.emit).toHaveBeenCalledWith('hello');
});

when your component is:

@Component({ ... })
class MyComponent {
  @Output myEventEmitter = new EventEmitter<string>();

  buttonClick() {
    this.myEventEmitter.emit('hello');
  }
}