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

如何使用@react-testing-library测试@mui/x-date-pickers?日期选择测试报错

解决MUI X DatePicker测试中无法定位日期的问题

你遇到的错误是因为MUI X DatePicker弹窗中的日期单元格不是用单独数字作为label,而是使用包含完整日期的aria-label;另外弹窗加载需要异步过程,同步查询会找不到元素。

修正方案:

  • 用异步查询方法(findByLabelText/waitFor)等待弹窗渲染完成
  • 定位日期时使用完整的日期aria-label(格式取决于本地化设置),或通过文本查找数字并结合上下文筛选

修改后的测试代码:

import React from "react";
import { render, fireEvent, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";

import { DatePicker } from '@mui/x-date-pickers/DatePicker'; // version 6.2.0
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';

test("renders DatePicker and selects date", async () => {
    const handleChange = jest.fn();
    render(
        <LocalizationProvider dateAdapter={AdapterDateFns}>
            <DatePicker
                label="Select a date"
                value={null}
                onChange={handleChange}
            />
        </LocalizationProvider>
    );

    // 打开日期选择器弹窗
    const input = screen.getByLabelText('Select a date');
    fireEvent.focus(input);

    // 方法1:通过完整aria-label定位(推荐,避免重复数字干扰)
    const targetDate = new Date(2023, 3, 15);
    // 构建对应aria-label,格式由date-fns和本地化决定,这里是英文格式
    const dateAriaLabel = targetDate.toLocaleDateString('en-US', {
        month: 'long',
        day: 'numeric',
        year: 'numeric'
    });
    const dateCell = await screen.findByLabelText(dateAriaLabel);
    
    // 方法2:如果确定当前月份只有一个15,也可以用文本查找
    // const dateCell = await screen.findByText('15');

    fireEvent.click(dateCell);

    // 验证回调被正确调用
    await waitFor(() => {
        expect(handleChange).toHaveBeenCalledWith(targetDate);
    });
});

额外说明:

  • 如果你的本地化是中文,aria-label格式会变成"2023年4月15日",需要对应调整toLocaleDateString的参数(比如'zh-CN')
  • 若要测试特定月份的日期,可通过DatePicker的defaultCalendarMonth属性预设弹窗打开时显示的月份,避免依赖当前系统时间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:22:36