Angular:我如何在茉莉花中测试@HostListener?

时间:2017-05-30 21:34:13

标签: angular unit-testing jasmine

我在angular的组件中有下一个代码:

@HostListener('window:scroll', []) onWindowScroll() {
  this.showScrollToTop = false;
}

我怎样才能在茉莉花中测试?如何启动窗口滚动事件?

3 个答案:

答案 0 :(得分:5)

测试窗口:滚动:

it('should do something on window scroll', () => {
  window.dispatchEvent(new Event('scroll'));
  expect(...)....
});

答案 1 :(得分:1)

您可以通过在窗口上调用scrollTo函数来尝试进行简单的JS滚动。

如果您想要滚动顶部,它将是:

window.scrollTo(0, 0);

<强>更新

var scrollEvent = document.createEvent('CustomEvent');
scrollEvent.initCustomEvent( 'scroll', false, false, null );

window.dispatchEvent(scrollEvent)

答案 2 :(得分:0)

 it('Focus over elements', () => {
    fixture.detectChanges();
    const event = new Event('click', { bubbles: true });
    const spyDocumentClick = spyOn(component, 'clickout').and.callThrough();
    component.clickout(event);
    expect(spyDocumentClick).toHaveBeenCalled();
 });