Jest + React:IntersectionObserver 模拟不起作用?

daw*_*awg 4 javascript unit-testing reactjs jestjs intersection-observer

在我的 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/>);
        ...
    }
});
Run Code Online (Sandbox Code Playgroud)

我的 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
    }
    ...
);
Run Code Online (Sandbox Code Playgroud)

然而,当我运行测试时,我得到TypeError: observer.current.disconnect is not a function;如果它运行的话也是如此observer.current.observe()。我尝试在 component.test.js 本身的 it() 块内测试它,方法是实例化 IntersectionObserver,然后调用这些方法,当我重新运行测试时,会显示相同的消息,因此错误看起来与 IntersectionObserver 的设置方式无关在组件.js 中。我没有正确嘲笑 IntersectionObserver 吗?如果是这样,我该如何修复它?

lis*_*tdm 6

我建议您将 a 替换arrow function为 a normal function,因为您需要使用new 运算符来创建InterceptionObserver对象:

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

//--> assign mock directly without jest.fn
window.IntersectionObserver = mock;
Run Code Online (Sandbox Code Playgroud)

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