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

使用React Testing Library测试MUI DataGrid组件失败求助

解决MUI DataGrid在React Testing Library测试中出现的高度检测错误

在使用React Testing Library测试MUI DataGrid组件时,出现以下错误:

MUI: useResizeContainer - The parent DOM element of the data grid has an empty height. Please make sure that this element has an intrinsic height. The grid displays with a height of 0px.

即使组件中已经给父容器设置了固定高度,测试依然失败,以下是可行的解决思路:

方案一:手动模拟父元素的高度计算

测试环境(jsdom)不会像浏览器一样自动计算CSS样式对应的实际高度,因此可以在渲染后手动设置父容器的高度属性,让DataGrid能正确获取尺寸:

import { render, screen, waitFor } from '@testing-library/react';
import DataGridDemo from 'src/components/DataGridDemo';

it('Test my DataGridDemo', async () => {
  render(<DataGridDemo />);
  // 获取DataGrid的父容器
  const gridParent = screen.getByRole('grid').parentElement;
  // 手动设置offsetHeight,模拟浏览器计算结果
  Object.defineProperty(gridParent, 'offsetHeight', { value: 350 });
  
  // 等待组件完成尺寸计算和渲染
  await waitFor(() => {
    expect(screen.getByText('John Doe')).toBeInTheDocument();
  });
});

方案二:Mock MUI内部的useResizeContainer钩子

直接mock掉DataGrid依赖的useResizeContainer钩子,返回预设的宽高值,跳过真实的尺寸检测逻辑:

import { render, screen, waitFor } from '@testing-library/react';
import DataGridDemo from 'src/components/DataGridDemo';
import { useResizeContainer } from '@mui/x-data-grid';

// Mock钩子,返回固定的宽高
jest.mock('@mui/x-data-grid', () => ({
  ...jest.requireActual('@mui/x-data-grid'),
  useResizeContainer: jest.fn(() => ({
    ref: jest.fn(),
    width: 350,
    height: 350,
    resizing: false,
    handleResize: jest.fn(),
  })),
}));

it('Test my DataGridDemo', async () => {
  render(<DataGridDemo />);
  await waitFor(() => {
    expect(screen.getByRole('grid')).toBeInTheDocument();
  });
});

方案三:使用测试包裹器提供高度上下文

创建一个包裹组件,给测试环境添加全局高度上下文,确保父容器的高度能被正确识别:

import { render, screen, waitFor } from '@testing-library/react';
import DataGridDemo from 'src/components/DataGridDemo';

// 自定义包裹器,提供基础高度上下文
const TestWrapper = ({ children }) => (
  <div style={{ height: '100%', minHeight: 400 }}>
    {children}
  </div>
);

it('Test my DataGridDemo', async () => {
  render(<DataGridDemo />, { wrapper: TestWrapper });
  await waitFor(() => {
    expect(screen.getByText('Max Zander')).toBeInTheDocument();
  });
});

补充说明

之前尝试的autoHeight、disableVirtualization等方法无效的原因:

  • autoHeight依赖组件内容渲染完成后计算高度,但测试环境中尺寸检测可能早于内容渲染
  • disableVirtualization仅关闭虚拟滚动,不影响ResizeContainer的高度检测逻辑
  • 普通的ResizeObserverMock可能未覆盖MUI内部对尺寸检测的全部依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 02:37:04