我创建了一个指令,它可以检测它所附加的元素外部是否存在mousedown事件。它是通过可观察来完成的:
@Output() clickOutside = new EventEmitter<void>();
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.eventSubscription = fromEvent(document, 'mousedown')
.subscribe((event: MouseEvent) => {
if (!this.elementRef.nativeElement.contains(event.target)) {
this.clickOutside.emit();
}
});
}
我正在尝试为其编写一个测试( Jasmine ),我使用以下模板创建了一个测试组件:
<div class="container" clickOutside></div>
<div class="another"></div>
当我模拟点击 .another 元素时,this.clickOutside.emit()
上有一个 spy ,预计会被调用,但事实并非如此。我的测试如下所示:
spyOn(directive.clickOutside, 'emit');
elementWithoutDirective.nativeElement.dispatchEvent(new Event('mousedown'));
fixture.detectChanges();
expect(directive.clickOutside.emit).toHaveBeenCalled();
这没有按预期工作,测试失败,调用了预期的 spy 发出。
测试有效,如果
elementWithoutDirective.nativeElement.dispatchEvent(new Event('mousedown'));
替换为
document.dispatchEvent(new Event('mousedown'));
我的假设是单击不会将事件冒泡到文档中。我该如何模拟这种行为?
最佳答案
您的假设是正确的:
the Event constructor creates an event that does not bubble by default.
要更改此行为,您可以传递第二个 eventInit参数:
new Event('mousedown', {bubbles: true})
关于 Angular 方向测试;单击元素不会触发单击文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093297/