You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Testing Library中模拟拖拽调整TextareaAutosize大小失败排查

解决Material UI TextareaAutosize组件拖拽resize测试问题

问题描述

测试Material UI的TextareaAutosize组件拖拽右下角调整大小时,模拟鼠标事件后textarea.style.height未发生变化,日志显示前后高度均为15px,未达到预期的高度增长效果。

问题原因

  1. 浏览器原生textarea的resize行为由浏览器内核处理,fireEvent模拟的鼠标事件无法直接触发这一原生逻辑。
  2. 鼠标事件的触发目标和流程不符合真实拖拽场景:拖拽过程中鼠标会离开textarea元素,需在document上触发mousemove和mouseup事件,而非仅在textarea上。
  3. textarea.style.height仅反映内联样式,浏览器原生resize可能不会修改内联样式,而是调整元素的计算高度。

解决方案

方案一:直接修改尺寸模拟resize状态

跳过模拟鼠标拖拽,直接修改textarea尺寸并触发组件更新,测试组件的响应表现:

it('should not glitch when resizing textarea', function test() {
  if (/jsdom/.test(window.navigator.userAgent)) {
    this.skip();
  }

  const { container } = render(<TextareaAutosize />);
  const textarea = container.querySelector<HTMLTextAreaElement>('textarea')!;

  console.log('before computed height: ', textarea.getBoundingClientRect().height);

  // 直接设置高度模拟resize后的状态
  textarea.style.height = '100px';
  // 触发组件更新
  fireEvent.resize(textarea);

  console.log('after computed height: ', textarea.getBoundingClientRect().height);
  // 添加断言验证组件无卡顿、状态正常
});

方案二:正确模拟原生拖拽事件流程

按照真实拖拽的事件顺序,在document上触发后续鼠标事件:

it('should not glitch when resizing textarea', function test() {
  if (/jsdom/.test(window.navigator.userAgent)) {
    this.skip();
  }

  const { container } = render(<TextareaAutosize />);
  const textarea = container.querySelector<HTMLTextAreaElement>('textarea')!;

  console.log('before computed height: ', textarea.getBoundingClientRect().height);

  const rect = textarea.getBoundingClientRect();
  // 定位到resize手柄区域(右下角偏移5px确保命中)
  const handleX = rect.right - 5;
  const handleY = rect.bottom - 5;

  // 按下鼠标在手柄位置
  fireEvent.mouseDown(textarea, { clientX: handleX, clientY: handleY, buttons: 1 });
  // 拖拽过程在document上触发mousemove
  fireEvent.mouseMove(document, { clientX: handleX + 50, clientY: handleY + 50, buttons: 1 });
  // 松开鼠标在document上
  fireEvent.mouseUp(document);

  console.log('after computed height: ', textarea.getBoundingClientRect().height);
});

关键提示

  • 使用getBoundingClientRect().height获取元素的实际计算高度,而非仅依赖style.height(后者仅显示内联样式)。
  • 若核心需求是测试组件resize后的表现而非原生拖拽逻辑,方案一更高效可靠,避免测试工具对原生事件模拟的局限性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:31:09