我正在尝试使用Jasmine和Angular测试一个在滚动上执行某些操作的角度指令。
这是指令代码:
@Directive({
selector: '[dfScroller]'
})
export class ScrollerDirective {
@select(['module', 'sessionTimeout', 'showTimeoutWarning']) readonly showTimeoutWarning$: Observable<any>;
debounceLastAction = debounce(() => { this.actions.updateLastActionTimestamp(); }, 1500);
constructor(private actions: ModuleActions) {}
hideToastComponent = () => {
if (convertObservableToList(this.showTimeoutWarning$)) {
this.actions.showTimeoutWarning(false);
}
}
@HostListener('window:scroll') scrolling() {
this.debounceLastAction();
this.hideToastComponent();
}
@HostListener('click') clicking() {
this.debounceLastAction();
this.hideToastComponent();
}
}
这是规范文件,我正在测试点击事件和滚动事件:
…
// Test case
describe('Directive: Scroller directive', async () => {
compileAndCreate();
it('Should be able to test the scroller directive on click', async () => {
const debounceLastActionSpy = spyOn(directiveInstance, 'debounceLastAction').and.callThrough();
const hideToastComponentSpy = spyOn(directiveInstance, 'hideToastComponent').and.callThrough();
directiveEl.nativeElement.click();
expect(debounceLastActionSpy).toHaveBeenCalled();
expect(hideToastComponentSpy).toHaveBeenCalled();
});
it('Should be able to test the scroller directive on mouse wheel', async () => {
const debounceLastActionSpy = spyOn(directiveInstance, 'debounceLastAction').and.callThrough();
const hideToastComponentSpy = spyOn(directiveInstance, 'hideToastComponent').and.callThrough();
directiveEl.nativeElement.scrollIntoView();
expect(debounceLastActionSpy).toHaveBeenCalled();
expect(hideToastComponentSpy).toHaveBeenCalled();
});
});
如果我评论滚动测试的期望部分和整个点击测试,我可以看到所涵盖的方法。但是一旦我添加了期望,我就会收到一条错误消息,说明该方法从未被调用过。
我已经尝试了几件事: - 用Karma运行单元测试,仍然出错。 - 从debounceLastAction中移除debounce,仍然出现错误。