gpt4 book ai didi

unit-testing - 使用 Jasmine、mouseenter/mouseleave-test 进行 Angular2 测试

转载 作者:太空狗 更新时间:2023-10-29 17:30:01 25 4
gpt4 key购买 nike

我有一个 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() {
}
}

现在,我收到消息:

Failed: div.mouseenter is not a function

那么,有人知道哪个是正确的功能(如果存在的话)吗?我已经尝试过使用 click()..

谢谢!

最佳答案

代替

div.mouseenter();

这应该有效:

let event = new Event('mouseenter');
div.dispatchEvent(event);

关于unit-testing - 使用 Jasmine、mouseenter/mouseleave-test 进行 Angular2 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com