在我的组件测试文件component.test.js中,我尝试通过以下方式来模拟IntersectionObserver:
我的 component.js 看起来像这样(实现了无限分页):
当我运行测试时,出现了
const mock = ()=>({
observe: jest.fn(),
disconnect: jest.fn()
});
window.IntersectionObserver = jest.fn().mockImplementation(mock);
describe("Component", ()=>{
it("test 1", ()=>{
render(<Component/>);
...
}
});
我的 component.js 看起来像这样(实现了无限分页):
//ref to last item loaded >> load more items once it enters view
const observer = useRef();
const lastEntryRef = useCallback((node)=>{
...
observer.current.disconnect(); //ERROR LINE
}
...
);
当我运行测试时,出现了
TypeError: observer.current.disconnect is not a function
的错误;如果observer.current.observe()
也运行,则同样报错。 我尝试在组件test.js的it()块中使用IntersectionObserver实例进行测试,然后调用那些方法,重新运行测试时显示相同的消息,因此这些错误看起来与如何在component.js中设置IntersectionObserver无关。 我没有正确地模拟IntersectionObserver吗? 如果是这样,我该怎么修复它?