Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to test EventEmitter in Angular2?

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?

like image 941
tallkid24 Avatar asked Feb 10 '16 15:02

tallkid24


People also ask

How do you test for EventEmitter?

We can take three approaches to testing the behavior of the EventEmitter from the perspective of the parent (the component listening for the event): Invoke the @Output property's emit method (since the EventEmitter is a public property) Dig in to the counter's DebugElement and simulate a click on the button.

How do you pass an event in Jasmine test case?

The correct syntax in this case would be let methodSpy = spyOn(component1, 'onChange'). and. callThrough(); and after you've triggered the method, expect(methodSpy). toHaveBeenCalled(); .

Are event emitters observables?

EventEmitter is used in the directives and components to emit custom events either synchronously or asynchronously. Since EventEmitter class extends RxJS subject class, this means it is observable and can be multicasted to many observers.

What is SpyOn in Angular unit testing?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.


1 Answers

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');   } } 
like image 144
cexbrayat Avatar answered Oct 18 '22 06:10

cexbrayat