Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Unit test that a component's output is not emitted

Let's say I have a component like the following:

@Component({
  selector: 'example',
  template: ` `
})
export class ExampleComponent {
  value: any;
  @Output() output: EventEmitter<any> = new EventEmitter();

  onValueChange(newValue: any) {
    if (newValue !== this.value) {
      this.value = newValue;
      this.output.emit(newValue);
    }
  }
}

I've written a test like the one below. I want to test that if onValueChange is called with the same value as value, the component will not output the duplicate value. Is there a best practice for unit testing that an observable subscription is never called? While what I did technically works, it feels a little hacky.

describe('ExampleComponent', () => {
  it('should not output duplicate values', () => {
    const component = new ExampleComponent();
    component.value = 1;
    component.output.subscribe(value => {
      // if the output is not triggered then we'll never reach this 
      // point and the test will pass
      expect(true).toEqual(false);
    });
    component.onValueChange(1);
  });
});
like image 452
Rich McCluskey Avatar asked Oct 18 '17 19:10

Rich McCluskey


2 Answers

You can use a spy like this:

describe('ExampleComponent', () => {
  it('should not output duplicate values', () => {
    const component = new ExampleComponent();        
    spyOn(component.output, 'emit');

    component.value = 1;
    component.onValueChange(1);

    expect(component.output.emit).not.toHaveBeenCalled();
  });
});
like image 86
Mohamed Gara Avatar answered Oct 30 '22 09:10

Mohamed Gara


That's pretty much how you do it. A variation is:

describe('ExampleComponent', () => {
  it('should not output duplicate values', () => {
    const component = new ExampleComponent();
    let numEvents = 0;
    component.value = 1;
    component.output.subscribe(value => ++numEvents);
    component.onValueChange(1);
    expect(numEvents).toEqual(0);
  });
});
like image 35
Brandon Avatar answered Oct 30 '22 09:10

Brandon