Menu

Angular Unit testing – spyOn – EventEmitter

If you have a Output that emits an event, below is the code for that

export class CustomDropdownComponent {
  @Input() Items: string[];
  @Output() onItemSelect = new EventEmitter<string>();
  constructor() { }

  onChange(item: string) {
    this.onItemSelect.next(item);
  }
}

Then you can unit test like this, you can spyOn the “onItemSelect” ‘s “next” emit

it('should emit "next" with parameter "Active" when onChange is called with "Active"', () => {
    const spy = spyOn(component.onItemSelect, 'next');
    component.onChange('Active');

    expect(spy).toHaveBeenCalledWith('Active');
  });

 

Leave a comment