如何在Angular上测试HostListener窗口滚动



我很难测试这个函数和这两个条件,有人能帮忙吗?

@HostListener('window:scroll', ['$event'])
onWindowScroll(event: Event) {
const numb = window.scrollY;
if (numb >= 50){
this.scrolled = true;
}
else {
this.scrolled = false;
}
}

我建议通过执行以下操作来注入窗口:

constructor(@Inject(DOCUMENT) private readonly document: Document) {
this.window = this.document.defaultView;
}
@HostListener('window:scroll', ['$event'])
onWindowScroll(event: Event) {
this.scrolled = this.window.scrollY >= 50;
}

然后,假设你使用Jasmine/Karma之类的东西来编写测试,那么在你的规范中,你可以注入窗口并发送假滚动事件来测试响应。

let mockWindow: any;
beforeEach(() => {
mockWindow = document.createElement('div');
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [{ provide: DOCUMENT, useValue: { defaultView: mockWindow } }]
});
});
it('responds to scroll events' () => {
Object.defineProperty(mockWindow, 'scrollY', { value: 100 });
mockWindow.dispatchEvent(new Event('scroll'));
expect(fixture.componentInstance.scrolled).toBe(true);
});

在这里,我还用defineProperty伪造了scrollY,以使测试正常。

注意事项:我并没有用@HostListener('window:scroll')做到这一点,但它对我使用@HostListener('window:resize')起到了作用,所以我想它也会起到类似的作用。我完全是徒手写的,所以如果复制/粘贴的话,我不会期望它能完美运行。

相关内容

最新更新