首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用userEvent测试呈现MUI选择的组件?

如何使用userEvent测试呈现MUI选择的组件?
EN

Stack Overflow用户
提问于 2022-11-21 17:23:13
回答 1查看 66关注 0票数 1

我正在为呈现材料UI选择的组件编写单元测试。但userEvent.selectOption似乎不起作用。在下面的示例中,两个getByRole调用似乎都选择了正确的组件,但是使用screen.getByText进行的验证无法找到文本,并且测试输出显示占位符选项仍然被选中。在Storybook中手动测试显示,我的组件按预期工作。我尝试过使用fireEvent的一些变体,但也没有任何进展。

TestSelect.tsx:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
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承诺解决之后):

代码语言:javascript
运行
复制
    <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>

包版本:

代码语言:javascript
运行
复制
"@mui/material": "5.10.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"vitest": "0.23.4"
EN

回答 1

Stack Overflow用户

发布于 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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74522691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档