我的应用程序中有一个(写得相当糟糕的)javascript 组件来处理无限滚动分页,我正在尝试重写它以使用 IntersectionObserver
,如 here 所述,但是我在测试它时遇到了问题。
有没有办法在 QUnit 测试中驱动观察者的行为,即用我的测试中描述的一些条目触发观察者回调?
我想到的一个可能的解决方案是在组件的原型(prototype)中公开回调函数并在我的测试中直接调用它,如下所示:
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;
});
关于javascript - JS - 使用 IntersectionObserver 的测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249985/