【问题标题】:Jest + React: IntersectionObserver mock not working?Jest + React:IntersectionObserver 模拟不起作用?
【发布时间】:2021-05-17 17:50:22
【问题描述】:

在我的 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() 也是如此。我尝试通过实例化 IntersectionObserver 然后调用这些方法在 component.test.js 本身的 it() 块中对其进行测试,当我重新运行测试时显示相同的消息,因此错误看起来与 IntersectionObserver 的设置方式无关在 component.js 中。我没有正确地嘲笑 IntersectionObserver 吗?如果是这样,我该如何解决?

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs intersection-observer


    【解决方案1】:

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

    const mock =  function() {
      return {
        observe: jest.fn(),
        disconnect: jest.fn(),
      };
    };
    
    //--> assign mock directly without jest.fn
    window.IntersectionObserver = mock;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-09
      • 2020-03-11
      • 2020-08-13
      • 1970-01-01
      • 2019-01-24
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多