You need to enable JavaScript to run this app. Jest中已完成Intersection Observer mock后如何触发指定元素的isIntersecting回调
优惠活动
大模型
产品
解决方案
定价
更多

Jest中已完成Intersection Observer mock后如何触发指定元素的isIntersecting回调

核心结论

完全可以实现。你当前的mock缺失了回调存储逻辑,改造后即可在测试用例中任意触发指定元素的交叉状态回调。

改造后的Mock实现

核心改动点:

  • 构造函数接收原生API要求的callback和配置参数
  • 维护观察项列表,存储每个目标元素对应的回调
  • 新增静态触发方法,供测试用例手动调用回调
export const setupIntersectionObserverMock = ({
  root = null,
  rootMargin = '',
  thresholds = [],
  // 兼容原有自定义mock函数,用于断言调用
  disconnect: customDisconnect = () => null,
  observe: customObserve = () => null,
  takeRecords: customTakeRecords = () => null,
  unobserve: customUnobserve = () => null,
} = {}) => {
  // 存储所有观察项,每个项包含目标元素、绑定的回调
  const mockObservers = [];

  class MockIntersectionObserver {
    // 原生API构造函数需要接收回调和配置
    constructor(callback, options = {}) {
      this.callback = callback;
      this.root = options.root || root;
      this.rootMargin = options.rootMargin || rootMargin;
      this.thresholds = options.thresholds || thresholds;
    }

    observe(target) {
      // 先执行用户传入的自定义observe mock,兼容原有断言逻辑
      customObserve(target);
      // 存入观察列表
      mockObservers.push({ target, callback: this.callback });
    }

    unobserve(target) {
      customUnobserve(target);
      const index = mockObservers.findIndex(item => item.target === target);
      if (index > -1) mockObservers.splice(index, 1);
    }

    disconnect() {
      customDisconnect();
      mockObservers.length = 0;
    }

    takeRecords() {
      return customTakeRecords();
    }

    // 新增静态触发方法,测试用例直接调用即可
    static trigger(target, entryOverrides = {}) {
      const matchedObserver = mockObservers.find(item => item.target === target);
      if (!matchedObserver) return;
      // 生成符合原生结构的IntersectionObserverEntry,支持自定义覆盖任意属性
      const entry = {
        isIntersecting: false,
        intersectionRatio: 0,
        boundingClientRect: target.getBoundingClientRect(),
        intersectionRect: {},
        rootBounds: this.root,
        target,
        time: Date.now(),
        ...entryOverrides,
      };
      matchedObserver.callback([entry], this);
    }
  }

  // 替换全局的IntersectionObserver
  Object.defineProperty(window, 'IntersectionObserver', {
    writable: true,
    configurable: true,
    value: MockIntersectionObserver,
  });
  Object.defineProperty(global, 'IntersectionObserver', {
    writable: true,
    configurable: true,
    value: MockIntersectionObserver,
  });

  return MockIntersectionObserver;
};
测试用例使用方式
const observe = jest.fn();
const disconnect = jest.fn();
// 初始化mock,返回Mock类用于后续触发回调
const MockIntersectionObserver = setupIntersectionObserverMock({ observe, disconnect });

const page = await newSpecPage({
  components: [TestComponent],
  html: `<div class="target"></div>`, // 这就是我要触发"isIntersecting"状态的目标元素
});
const targetEl = page.root.querySelector('.target');

// 手动触发该元素的交叉状态,设置isIntersecting为true
MockIntersectionObserver.trigger(targetEl, { isIntersecting: true });

// 后续正常断言组件的对应行为即可
// 例:expect(observe).toHaveBeenCalledWith(targetEl)
// 例:expect(page.root.querySelector('.visible-state')).toBeTruthy()
  • 如果需要触发isIntersecting为false的状态,只需在trigger的第二个参数传入{ isIntersecting: false }即可
  • 还可以自定义intersectionRatio等其他IntersectionObserverEntry属性,模拟不同的交叉场景

内容的提问来源于stack exchange,提问作者maidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.13 16:54:03