我正在为呈现材料UI选择的组件编写单元测试。但userEvent.selectOption
似乎不起作用。在下面的示例中,两个getByRole
调用似乎都选择了正确的组件,但是使用screen.getByText
进行的验证无法找到文本,并且测试输出显示占位符选项仍然被选中。在Storybook中手动测试显示,我的组件按预期工作。我尝试过使用fireEvent
的一些变体,但也没有任何进展。
TestSelect.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>
);
}
TestSelect.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();
});
根据测试输出,下面是断言发生时DOM的相关部分(在selectOptions
承诺解决之后):
<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>
包版本:
"@mui/material": "5.10.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"vitest": "0.23.4"
发布于 2022-11-23 23:54:48
通常,在执行一个操作之后,您希望等待它完成。最好的方法是使用screen.findBy
,它在引擎盖下使用waitFor()
。所以就像这样:
expect(await screen.findByText('thing: One')).toBeInTheDocument();
另外,另一个断言可以是检查是否选择了该选项:
expect(await screen.findByRole('option', { name: 'One' }).selected).toBe(true)
https://stackoverflow.com/questions/74522691
复制相似问题