Search code examples
unit-testingangularangular2-directivesangular2-testing

Angular2 testing with Jasmine, mouseenter/mouseleave-test


I've got a HighlightDirective which does highlight if the mouse enters an area, like:

@Directive({
  selector: '[myHighlight]',
  host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
  private _defaultColor = 'Gainsboro';
  private el: HTMLElement;

  constructor(el: ElementRef) { this.el = el.nativeElement; }

  @Input('myHighlight') highlightColor: string;

  onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); }
  onMouseLeave() { this.highlight(null); }

  private highlight(color:string) {
    this.el.style.backgroundColor = color;
  }

}

Now I want to test, if the (right) methods are called on event. So something like this:

  it('Check if item will be highlighted', inject( [TestComponentBuilder], (_tcb: TestComponentBuilder) => {
    return _tcb
      .createAsync(TestHighlight)
      .then( (fixture) => {
        fixture.detectChanges();
        let element = fixture.nativeElement;
        let component = fixture.componentInstance;
        spyOn(component, 'onMouseEnter');
        let div = element.querySelector('div');


        div.mouseenter();


        expect(component.onMouseEnter).toHaveBeenCalled();
      });
  }));

With the testclass:

@Component({
  template: `<div myHighlight (mouseenter)='onMouseEnter()' (mouseleave)='onMouseLeave()'></div>`,
  directives: [HighlightDirective]
})
class TestHighlight {
  onMouseEnter() {
  }
  onMouseLeave() {
  }
}

Now, I've got the message:

Failed: div.mouseenter is not a function

So, does anyone know, which is the right function (if it exists)? I've already tried using click()..

Thanks!


Solution

  • Instead of

    div.mouseenter();
    

    this should work:

    let event = new Event('mouseenter');
    div.dispatchEvent(event);