【发布时间】:2017-10-25 11:01:06
【问题描述】:
我对 Jasmine 测试很陌生,我正在尝试测试一个指令来处理鼠标事件,如鼠标向下、向上和移动。我的问题是如何将 Jasmine 规范中的鼠标坐标传递给我的指令并模拟鼠标事件。我已经在这个主题上进行了很多搜索,但除了this 之外,我找不到任何示例,它不做任何事情,比如传递元素的坐标。
以下是我在 Angular 中使用 TestBed 配置编写测试的尝试:
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 作为事件传递。这将成功执行并运行我的测试,但我想通过从这里传递鼠标坐标来模拟鼠标事件。谁能给我一些资源或指出正确的方向如何实现这一目标,或者如果无法实现,我可以研究哪些替代方案。
任何帮助将不胜感激。
谢谢。
塔米冈萨雷斯
【问题讨论】:
标签: javascript angular unit-testing jasmine