Jest + React:IntersectionObserver模拟无效?

4
在我的组件测试文件component.test.js中,我尝试通过以下方式来模拟IntersectionObserver:
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吗? 如果是这样,我该怎么修复它?
1个回答

5

我建议您使用普通函数替换箭头函数,因为您需要使用new操作符来创建InterceptionObserver对象:

const mock =  function() {
  return {
    observe: jest.fn(),
    disconnect: jest.fn(),
  };
};

//--> assign mock directly without jest.fn
window.IntersectionObserver = mock;

您可以检查是否已调用window.InterceptionObserver.observe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接