Angular2 testing with Jasmine, mouseenter/mouseleave-test
Asked Answered
I

3

6

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!

Improvvisatore answered 28/6, 2016 at 7:3 Comment(0)
D
21

Instead of

div.mouseenter();

this should work:

let event = new Event('mouseenter');
div.dispatchEvent(event);
Down answered 28/6, 2016 at 8:42 Comment(0)
R
0

additional info to gunter's answer, you need to send additional parameter to the Event. Or it won't trigger. Refer to: https://developer.mozilla.org/en-US/docs/Web/API/Event/composed

let event = new Event('mouseenter', {composed: true}); would be the correct way of defining the event for the HTMLElement to invoke the Event.

Rudie answered 17/6, 2020 at 16:12 Comment(0)
T
0

Additionally as well, I had missed the following from the create component:

fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();  // <<< THIS

If you do it will appear like the test is working, but by using coverage, you will find the event is not triggered. A nasty issue to spot.

Twayblade answered 16/10, 2020 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.