如何使用 React 测试库为 Material UI 中的选项卡编写测试用例?

Gow*_*ena 6 reactjs material-ui react-testing-library

我在应用程序中使用 Material UI 选项卡并使用 React 测试库。我需要编写用于从一个选项卡导航到另一个选项卡的测试用例。任何人都可以帮我解决这个问题,因为下面的代码无法正常工作。提前致谢。

代码:

const [value, setValue] = React.useState(0)

function handleChange(event, newValue) {
  setValue(newValue)
}
Run Code Online (Sandbox Code Playgroud)
<AntTabs value={value} onChange={handleChange} aria-label="Unit information">
  <AntTab label="HELLOW1" {...unitTabProps(0)} />
  <AntTab label="HELLOW2" {...unitTabProps(1)} />
  <AntTab label="HELLOW3" {...unitTabProps(2)} />
  <AntTab label="HELLOW4" {...unitTabProps(3)} />
  <AntTab label="HELLOW5" {...unitTabProps(4)} />
</AntTabs>
Run Code Online (Sandbox Code Playgroud)

小智 13

我相信 Material ui 选项卡具有 role="tab" 属性。通过说,您可以尝试按角色获取选项卡。请参阅https://testing-library.com/docs/queries/byrole

对于您的情况,您可以尝试以下操作:

const tab = screen.getByRole('tab', { name: 'HELLOW2' });
fireEvent.click(tab);
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent('HELLOW2');
Run Code Online (Sandbox Code Playgroud)


Rom*_*ian 3

这是一个测试,用于检查当我们单击第二个选项卡时它是否被选中:

it("activates second tab when clicking on it", () => {
  const { getByText } = render(<YourComponent />);
  const hellow1 = getByText("HELLOW1").closest("button");
  const hellow2 = getByText("HELLOW2").closest("button");
  expect(hellow1).toHaveAttribute("aria-selected", "true");
  expect(hellow2).toHaveAttribute("aria-selected", "false");
  fireEvent.click(hellow2);
  expect(hellow1).toHaveAttribute("aria-selected", "false");
  expect(hellow2).toHaveAttribute("aria-selected", "true");
});
Run Code Online (Sandbox Code Playgroud)

您可能不需要进行此测试,因为 Material UI 选项卡已经过测试,但您可以通过代码来测试您的功能。