我有一个 HighlightDirective,如果鼠标进入一个区域,它会突出显示,例如:
@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;
}
}
现在我想测试是否在事件中调用了(正确的)方法。所以是这样的:
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();
});
}));
使用测试类:
@Component({
template: `<div myHighlight (mouseenter)='onMouseEnter()' (mouseleave)='onMouseLeave()'></div>`,
directives: [HighlightDirective]
})
class TestHighlight {
onMouseEnter() {
}
onMouseLeave() {
}
}
现在,我得到了消息:
失败:div.mouseenter 不是函数
那么,有谁知道,哪个是正确的功能(如果存在)?我已经尝试过使用 click() ..
谢谢!