I have created a directive that it detects whether there has been a mousedown event outside the element that it is attached too. It is done with an observable:
@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();
}
});
}
I am trying to write a test (jasmine) for it, I created a test component with the following template:
<div class="container" ganSharedClickOutside></div>
<div class="another"></div>
When I mock a click on the .another element, there is a spy on on this.clickOutside.emit()
that is expected to have been called, which is not the case. My test looks like this:
spyOn(directive.clickOutside, 'emit');
elementWithoutDirective.nativeElement.dispatchEvent(new Event('mousedown'));
fixture.detectChanges();
expect(directive.clickOutside.emit).toHaveBeenCalled();
This doesn't work as expected and the test fails with Expected spy emit to have been called.
The test works if
elementWithoutDirective.nativeElement.dispatchEvent(new Event('mousedown'));
is replaced with
document.dispatchEvent(new Event('mousedown'));
My assumption is that the click doesn't bubble up the event to the document. How can I model this behaviour?
Aucun commentaire:
Enregistrer un commentaire