userEvent测试Material UI Select组件失效,该如何解决?
Material UI Select组件测试中userEvent.selectOptions不生效的解决方案
问题重现
测试MUI Select组件时,调用userEvent.selectOptions选择选项后,组件状态未更新,断言screen.getByText('thing: One')失败。DOM显示占位符选项仍处于选中状态,但手动在Storybook中测试功能正常。
核心原因
MUI的Select组件并非基于原生<select>元素实现,而是通过自定义的Listbox/MenuItem结构渲染下拉选项。userEvent.selectOptions是专门针对原生<select>的API,无法正确触发MUI自定义组件的onChange事件。
解决方案
模拟真实用户的交互行为,直接点击下拉选项即可触发状态更新:
修改后的测试代码:
import userEvent from '@testing-library/user-event'; import { render, screen } from '@testing-library/react'; import { TestSelect } from './TestSelect'; it('select option', async () => { const user = userEvent.setup(); render(<TestSelect />); // 点击打开下拉菜单 await user.click(screen.getByRole('button')); // 点击目标选项 await user.click(screen.getByRole('option', { name: 'One' })); expect(screen.getByText('thing: One')).toBeInTheDocument(); });
额外说明
- 若尝试使用
fireEvent,需确保触发的是click事件而非change事件,因为MUI的选项选择逻辑绑定在点击事件上。 - 避免使用针对原生表单组件的API测试MUI自定义组件,始终优先模拟真实用户的操作流程。
内容的提问来源于stack exchange,提问作者Tom Faber
相关产品推荐
相关产品推荐

