【问题标题】:How do I use userEvent to test a component that renders a MUI Select?如何使用 userEvent 测试呈现 MUI Select 的组件?
【发布时间】:2022-11-24 08:12:00
【问题描述】:

我正在为呈现 Material UI Select 的组件编写单元测试。但是userEvent.selectOption 似乎不起作用。在下面的示例中,getByRole 调用似乎都选择了正确的组件,但 screen.getByText 的验证未能找到文本,测试输出显示占位符选项仍处于选中状态。在 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();
});

包版本:

"@mui/material": "5.10.5",
"@testing-library/react": "13.4.0",
"@testing-library/user-event": "14.4.3",
"vitest": "0.23.4"

【问题讨论】:

    标签: reactjs material-ui react-testing-library vitest user-event


    【解决方案1】:

    通常,执行一个操作后,您希望等待它完成。最好的方法是使用screen.findBy,它在底层使用waitFor()。所以像这样:

    expect(await screen.findByText('thing: One')).toBeInTheDocument();

    此外,另一个断言可能是检查该选项是否被选中:

    expect(await screen.findByRole('option', { name: 'One' }).selected).toBe(true)

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 2017-08-29
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-23
      • 2021-06-23
      • 2015-12-18
      相关资源
      最近更新 更多