我有一个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();
});
}));
使用testclass:
@Component({
template: `<div myHighlight (mouseenter)='onMouseEnter()' (mouseleave)='onMouseLeave()'></div>`,
directives: [HighlightDirective]
})
class TestHighlight {
onMouseEnter() {
}
onMouseLeave() {
}
}
现在,我收到了消息:
失败:div.mouseenter不是函数
那么,有谁知道,哪个是正确的功能(如果存在)?我已经尝试过使用click()..
谢谢!
答案 0 :(得分:16)
而不是
div.mouseenter();
这应该有效:
let event = new Event('mouseenter');
div.dispatchEvent(event);
答案 1 :(得分:0)
枪手回答的其他信息,您需要向事件发送其他参数。否则它不会触发。 请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Event/composed
let event = new Event('mouseenter',{composed:true}); 将是为HTMLElement定义事件以调用事件的正确方法。
答案 2 :(得分:0)
此外,我还错过了create组件中的以下内容:
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges(); // <<< THIS
如果执行此操作,则好像测试正在运行,但是通过使用覆盖率,您会发现未触发事件。 一个令人讨厌的问题。