Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2. Emitting hover event in unit tests

I have template for some (MyCmp) component(<my-cmp></my-cmp>) like this

<template ngFor let-r [ngForOf]="range" let-index="index">
  <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span>
  <i (mouseenter)="somefunc()" (click)="elefunc()"></i>
  ....
</template>

I configure TestBed for MyCmp component via special TestComponent

TestBed.configureTestingModule({declarations: [TestComponent], imports: [MyModule]}
TestBed.overrideComponent(TestComponent, {set: {template: '<my-cmp></my-cmp>'}});
fixture = TestBed.createComponent(TestComponent);
context = fixture.debugElement.componentInstance;
element = fixture.nativeElement;
fixture.detectChanges();

I think it's not important. Tests worked.

element.querySelectorAll('i')[0].click(); //fine

But i don't know how i should emit hover(mouseenter) and mouseleave event

element.querySelectorAll('i')[0].hover() // not a function
element.querySelectorAll('i')[0].mouseover() // not a function
element.querySelectorAll('i')[0].createMouseEvent('mouseover') // not a function
like image 448
Oleg Rybnikov Avatar asked Nov 25 '16 12:11

Oleg Rybnikov


People also ask

What does fixture detectChanges () do?

fixture. detectChanges() tells Angular to run change-detection. Finally! Every time it is called, it updates data bindings like ng-if, and re-renders the component based on the updated data. Calling this function will cause ngOnInit to run only the first time it is called.

What is beforeEach in Angular testing?

beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite. In this test suite, beforeEach is used to create a testing module using the TestBed object and declares any components that would be used in this testing module.

How do you trigger event in Jasmine?

According to the Angular Testing documentation, to trigger the events from the tests, we use the triggerEventHandler() method on the debug element. This method takes the event name and the object . Now, this works if we are adding the events using the HostListener .

What is fakeAsync in Angular?

fakeAsynclinkWraps a function to be executed in the fakeAsync zone: Microtasks are manually executed by calling flushMicrotasks() . Timers are synchronous; tick() simulates the asynchronous passage of time.


1 Answers

In case you haven't had an answer for this, you can use the dispatchEvent of the nativeElement in the following way:

element.dispatchEvent(new MouseEvent('mouseover', {
    view: window,
    bubbles: true,
    cancelable: true
}));
like image 90
Saturn K Avatar answered Nov 02 '22 00:11

Saturn K