首页 > 解决方案 > 如何从笑话中调用 IntersectionObserver 回调函数?

问题描述

用于延迟图像加载的新 Intersection Observer 的 Js 代码。

_observer = new IntersectionObserver(function (entries) {
    entries.forEach(function (entry) {
      if (entry.intersectionRatio > 0) {
        let lazyImage = entry.target;
        lazyImage.removeAttribute('class');
        _observer.unobserve(lazyImage);
      }
    });

笑话代码:

 beforeAll(() => {
  const options = {
    threshold: 0.1,
  };

  window.IntersectionObserver = jest.fn(function () {
    observe, unobserve;
  }, options);

  wrapper = mount(<Image url="test.jpg" alt="test" />);
});

afterAll(() => {
  window.IntersectionObserver = windowIntersectionObserver;
});
 it('creates an observer on the element ref', () => {
  expect(observe).toHaveBeenCalled();
});
 

o/p:

  Expected number of calls: >= 1
  Received number of calls:    0

这对我不起作用。如何从 Jest 代码中调用交叉点观察者。我检查了类似的问题,它在这里不起作用

标签: reactjsjestjsintersection-observer

解决方案


推荐阅读