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

升级至MUI X v5后DatePicker组件单元测试无法触发onChange处理函数

问题原因

MUI X v5的DatePicker组件对输入交互做了封装,直接用fireEvent.change触发输入框变更事件不会直接触发顶层的onChange回调,核心有两个原因:

  • 组件内置了日期格式校验逻辑,只有输入内容符合inputFormat要求且校验通过后才会提交变更
  • 默认输入变更不会立刻触发回调,需要输入框失焦,或者用户主动在弹窗面板选择日期才会触发onChange
解决方案

按照以下步骤修改测试代码即可:

步骤1:安装并引入userEvent

@testing-library/user-event模拟的是真实用户交互行为,比底层的fireEvent更符合组件的交互触发逻辑

npm install @testing-library/user-event@14 --save-dev

测试文件顶部补充引入依赖:

import userEvent from '@testing-library/user-event'
import { render, fireEvent, waitFor } from "@testing-library/react"

步骤2:修改测试用例逻辑

输入完成后主动触发失焦事件,同时用waitFor包裹断言等待异步状态更新,修改后的用例参考:

it("should call handler when start date is updated", async () => {
  const user = userEvent.setup()
  const startInput = c.getByTestId("start-date-picker").querySelector('input')
  await user.type(startInput, "01/03/2000")
  // 触发失焦让组件校验输入内容
  fireEvent.blur(startInput)
  // 等待异步回调触发
  await waitFor(() => {
    expect(handleStartDateChangeMock).toHaveBeenCalledWith(expect.any(Date), "01/03/2000")
  })
})

it("should call handler when end date is updated", async () => {
  const user = userEvent.setup()
  const endInput = c.getByTestId("end-date-picker").querySelector('input')
  await user.type(endInput, "01/04/2000")
  fireEvent.blur(endInput)
  await waitFor(() => {
    expect(handleEndDateChangeMock).toHaveBeenCalledWith(expect.any(Date), "01/04/2000")
  })
})
额外优化建议

你当前组件中空值时给maxDate/minDate传了空字符串,不符合日期适配器的预期规范,建议改成传null避免潜在的解析异常:

maxDate={endDateValue ? formatDate(endDateValue) : null}
minDate={startDateValue ? formatDate(startDateValue) : null}

内容的提问来源于stack exchange,提问作者Manoj Kumar Mohan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:36:01