How to test a directive with a mouse wheel event in angular 2 / 4

Tums picture Tums · Jun 2, 2017 · Viewed 11.7k times · Source

I have a directive which has a mouse wheel event, it is used to zoom in and out a canvas. I would like to know how can I write a unit test for such an event. I couldn't find any example online, could anyone point me in a right direction?

My directive:

import { Directive, ElementRef, HostListener} from "@angular/core";
import { MyService } from "./my-service";
@Directive({
    selector: "[testDirec]"
})
export class Test {
  private initPointX: number;
  private initPointY: number;

  constructor(private ele: ElementRef,
        private serviceInstance: MyService) {
    }

    @HostListener('mousewheel', ['$event'])
    scroll(event: MouseEvent) {
        console.log("Entered mouse wheel");
        let wheelDelta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
        if(wheelDelta > 0) {
          factor = 0.5;
        }else {
         factor = 2.0;
        }

        this.initPointX = event.PageX;
        this.initPointY = event.PageY;   
    } 

}

Answer

Aravind picture Aravind · Jun 3, 2017

You should be using transform and test it. as below

<div scrollstyle="height:1000px;background-color:red">
      <input type="text" value=""/>
</div>



@Directive({
    selector: '[scroll]'
})
export class ChangeDirective{
 i:number=1;
    constructor(
        private renderer: Renderer,
        private el: ElementRef
    ){}

    @HostListener('mousewheel', ['$event']) onMousewheel(event) {
      if(event.wheelDelta>0){
          event.srcElement.style.setProperty('transition','all 200ms ease-in')
          event.srcElement.style.setProperty('transform',"scale(" + this.i+1 +")")
      }
      if(event.wheelDelta<0){
        event.srcElement.style.setProperty('transition','all 200ms ease-out')
        event.srcElement.style.setProperty('transform',"scale(" + this.i-1 +")")
      }
    }
}

LIVE DEMO