
[英]How to do an integration test for a material UI <Slider /> component with userEvent or fireEvent?
[英]How do I use userEvent to test a component that renders a MUI Select?
我正在为呈现 Material UI Select 的组件编写单元测试。但是userEvent.selectOption
似乎不起作用。 在下面的示例中,两个getByRole
调用似乎都选择了正确的组件,但是使用screen.getByText
进行的验证未能找到文本,测试 output 显示占位符选项仍处于选中状态。 在 Storybook 中手动测试显示我的组件按预期工作。 我已经尝试了一些使用fireEvent
的变体,但也没有成功。
测试选择.tsx:
import { Box, Select } from '@mui/material';
import { useState } from 'react';
export function TestSelect() {
const [thing, setThing] = useState('');
return (
<Box>
<Select
placeholder="hi"
onChange={(evt) => {
setThing(evt.target.value);
}}
value={thing}
>
<option key="" value="">hi</option>
<option value="One">One</option>
<option value="Two">Two</option>
</Select>
<div>{thing && `thing: ${thing}`}</div>
</Box>
);
}
测试选择.test.tsx:
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import { TestSelect } from './TestSelect';
it('select option', async () => {
const { click, selectOptions } = userEvent.setup();
render(<TestSelect />);
await click(screen.getByRole('button'));
await selectOptions(
screen.getByRole('listbox'),
screen.getByRole('option', { name: 'One' })
);
// next line throws "Unable to find an element with the text: thing: One."
expect(screen.getByText('thing: One')).toBeInTheDocument();
});
根据测试 output,这里是断言发生时 DOM 的相关部分(在selectOptions
promise 解决后):
<ul
class="MuiList-root MuiList-padding MuiMenu-list css-6hp17o-MuiList-root-MuiMenu-list"
role="listbox"
tabindex="-1"
>
<option
aria-selected="true"
data-value=""
role="option"
tabindex="0"
>
hi
</option>
<option
aria-selected="false"
data-value="One"
role="option"
>
One
</option>
<option
aria-selected="false"
data-value="Two"
role="option"
>
Two
</option>
</ul>
package 版本:
"@mui/material": "5.10.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"vitest": "0.23.4"
通常,执行一个操作后,您希望等待它完成。 执行此操作的最佳方法是使用screen.findBy
,它在后台使用waitFor()
。 所以像这样:
expect(await screen.findByText('thing: One')).toBeInTheDocument();
此外,另一个断言可能是检查该选项是否被选中:
expect(await screen.findByRole('option', { name: 'One' }).selected).toBe(true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.