Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 开玩笑+;反应:IntersectionObserver模拟不工作?_Javascript_Reactjs_Unit Testing_Jestjs_Intersection Observer - Fatal编程技术网

Javascript 开玩笑+;反应:IntersectionObserver模拟不工作?

Javascript 开玩笑+;反应:IntersectionObserver模拟不工作?,javascript,reactjs,unit-testing,jestjs,intersection-observer,Javascript,Reactjs,Unit Testing,Jestjs,Intersection Observer,在我的component.test.js中,我尝试通过如下方式模拟IntersectionObserver: const mock = ()=>({ observe: jest.fn(), disconnect: jest.fn() }); window.IntersectionObserver = jest.fn().mockImplementation(mock); describe("Component", ()=>{ it(&q

在我的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/>);
        ...
    }
});

然而,当我运行测试时,我得到
类型错误:observer.current.disconnect不是一个函数
;如果运行的话,
observer.current.observe()
也是如此。我尝试在component.test.js本身的it()块中测试它,方法是实例化IntersectionObserver,然后调用这些方法,并在重新运行测试时显示相同的消息,因此错误看起来与在component.js中如何设置IntersectionObserver无关。我不是在嘲笑IntersectionObserver吗?如果是,我该如何修复它?

我建议您将
箭头函数
替换为
正常函数
,因为您需要使用来创建
拦截观察者
对象:

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

//--> assign mock directly without jest.fn
window.IntersectionObserver = mock;
您可以检查是否调用了
窗口.InterceptionObserver.observe

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

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