【问题标题】:Unit Test Angular for HostListenerHostListener 的单元测试角度
【发布时间】:2021-09-24 22:18:00
【问题描述】:
我需要为@HostListener 创建单元测试,但我不知道如何编写它,因为它位于组件之上,
@HostListener('document:click', ['$event']) onDocumentClick(event) {
if (this.activeEvent) {
this.activeEvent = '';
} else {
this.showList = false;
}
this.resetDropdown(event.target.id);
}
为这种情况编写单元测试的最佳方式是什么?
【问题讨论】:
标签:
javascript
angular
unit-testing
jasmine
【解决方案1】:
你可以试试:
// feel free to change `body` to whatever you wish to send the click to
const body = fixture.nativeElement.querySelector('body');
body.click();
// see if `onDocumentClick` gets called that way
你有另一个选择,因为 @HostListener 已经被 Angular 测试过,你可以用你的模拟对象调用 onDocumentClick。
const resetSpy = spyOn(component, 'resetDropdown');
const mockedEvent = { target: { id: 'xyz' } };
component.onDocumentClick(mockedEvent);
expect(resetSpy).toHaveBeenCalledWith('xyz');