我的应用程序中有一个处理无限滚动分页的 JavaScript 组件,我正在尝试重写它以使用IntersectionObserver
,如上所述here https://developers.google.com/web/updates/2016/04/intersectionobserver,但是我在测试它时遇到了问题。
有没有办法在 QUnit 测试中驱动观察者的行为,即用我的测试中描述的一些条目触发观察者回调?
我提出的一个可能的解决方案是在组件的原型中公开回调函数并在我的测试中直接调用它,如下所示:
InfiniteScroll.prototype.observerCallback = function(entries) {
//handle the infinite scroll
}
InfiniteScroll.prototype.initObserver = function() {
var io = new IntersectionObserver(this.observerCallback);
io.observe(someElements);
}
//In my test
var component = new InfiniteScroll();
component.observerCallback(someEntries);
//Do some assertions about the state after the callback has been executed
我不太喜欢这种方法,因为它暴露了组件使用IntersectionObserver
在内部,我认为这是一个实现细节,客户端代码不应该看到它,那么有没有更好的方法来测试它(最好不使用 jQuery)?
由于我们正在使用 TypeScript 和 React (tsx) 的配置,所以发布的答案都不适合我。这是最终起作用的:
beforeEach(() => {
// IntersectionObserver isn't available in test environment
const mockIntersectionObserver = jest.fn();
mockIntersectionObserver.mockReturnValue({
observe: () => null,
unobserve: () => null,
disconnect: () => null
});
window.IntersectionObserver = mockIntersectionObserver;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)