如何在Angular 2或4中的Jasmine测试中模拟鼠标事件 [英] How to simulate mouse events in Jasmine tests in Angular 2 or 4

查看:284
本文介绍了如何在Angular 2或4中的Jasmine测试中模拟鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Jasmine测试很陌生,我正在尝试测试处理鼠标事件的指令,如鼠标按下,向上和移动。我的问题是如何将鼠标坐标从Jasmine规范传递到我的指令并模拟鼠标事件。我在这个主题上搜索了很多,但我找不到任何例子,除了这个没有做任何事情,比如传递元素的坐标。

I am pretty new to Jasmine testing and I am trying to test a directive which handles mouse events like mouse down, up and move. My question is how can I pass mouse coordinates from the spec of Jasmine to my directive and simulate the mouse events. I have searched a lot on this topic but I couldn't find any examples except for this one which doesn't do anything like passing the coordinates of the element.

以下是我尝试使用Angular中的TestBed配置编写测试:

The following is my attempt to write the test using the TestBed configuration in Angular:

import { Component, Directive, DebugElement } from "@angular/core";
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
import { TestDirective } from "./test";
import { MyService } from "./my-service";

@Component({
    template: `<div testDirec style="height:800px; width:500px; background-color:blue;"></div>`
})
class DummyComponent { }

export default function () {
    describe('Directive: Zoom', () => {
        let fixture: ComponentFixture<TestComponent>;
        let debugEle: DebugElement[];

        beforeAll(() => {
          TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

        }

        beforeEach(() => {
            TestBed.configureTestingModule({
                declarations: [TestDirective, DummyComponent],
                providers: [MyService]
            });
            fixture = TestBed.createComponent(DummyComponent);
            fixture.detectChanges();
            debugEle = fixture.debugElement.queryAll(By.directive(TestDirective));
        });

        it('mousedown on the div', () => {
            debugEle[0].triggerEventHandler('mousedown', null);
            expect(debugEle[0].nativeElement.style.width).toBe('500px');
        });

        it('mousemove on the div', () => {
            debugEle[0].triggerEventHandler('mousemove', null);
          expect(debugEle[0].nativeElement.style.backgroundColor).toBe('blue');
        });

    });

}

我的指令如下:

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('mousedown', ['$event'])
    onMouseDown(event: MouseEvent) {
        console.log("Entered mouse down");
        this.initPointX = event.PageX;
        this.initPointY = event.PageY;
        if (event.ctrlKey) {
            // do something
        }
    } 

    @HostListener('mousedown', ['$event'])
    onMouseMove(event: MouseEvent) {
        console.log("Entered mouse move");
        if (this.initPointX && this.initPointY) {
            // calculate the new mouse x and y coordinates and compute the difference to move the object.
        }
    } 
 //other functions.

}



如你所见在我的测试规范中,我将null作为事件传递。这将成功执行并运行我的测试,但我想通过从这里传递鼠标坐标来模拟鼠标事件。任何人都可以给我一些资源或指出我正确的方向如何实现这一点,或者如果无法实现我可以研究的替代方案。


As you can see inside my test spec, I am passing the null as the event. This will successfully execute and run my tests but instead I would like to simulate the mouse events by passing the mouse coordinates from here. Could anyone give me some resources or point me in a right direction how to achieve this or if it cannot be achieved what alternatives I can look into.

任何帮助都将不胜感激。

Any help would be greatly appreciated.

谢谢。

Tammy Gonzalez

Thank you.
Tammy Gonzalez

推荐答案

我不明白为什么你在 triggerEventHandler 中传递 null 。相反,你应该传递一个对象。根据你的指令,对象应该是 pageX pageY mousedown mousemove 事件。

I don't understand why you are passing null in your triggerEventHandler. Instead you should be passing an object. According to your directive, the object should be pageX and pageY values for both the mousedown and the mousemove events.

该指令将接收这些值并执行步骤你的逻辑,然后你可以期待价值。 expect 你当前没有任何意义,因为他们没有测试与鼠标事件相关的任何内容。

The directive will receive these values and will execute the steps of your logic and then you can expect the value. The expect's which you have currently doesn't make any sense as they don't test anything related to the mouse events.

我相信您正在寻找以下类型的规格:

I believe the following type of spec is what you are looking for:

it('mousedown on the div', inject([MyService], service) => {
     debugEle[0].triggerEventHandler('mousedown',{pageX:50, pageY: 40});
     debugEle[0].triggerEventHandler('mousemove',{pageX:60, pageY: 50});
     // assuming you are calculating the difference between the second and first objects.
     expect(service.someObj).toBe({x:10, y:10});
 });

以上代码很粗但我希望它有用。

The above code is crude but I hope it's helpful.

谢谢。

这篇关于如何在Angular 2或4中的Jasmine测试中模拟鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆