Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 632
bene Avatar asked Jun 28 '16 07:06

bene


1 Answers

Instead of

div.mouseenter();

this should work:

let event = new Event('mouseenter');
div.dispatchEvent(event);
like image 147
Günter Zöchbauer Avatar answered Nov 18 '22 09:11

Günter Zöchbauer