【问题标题】:Testing material-ui TextField by role using react-testing-library使用 react-testing-library 按角色测试 material-ui TextField
【发布时间】:2021-06-28 12:38:14
【问题描述】:

我有一些组件,其中包括一些mui TextFields,我的组件有两种情况:

  1. 一个TextField 是为LicenseCode 设计的,它不能有标签。

  2. 还有一些 TextFields 将通过 map 函数创建,我也不能为它们中的每一个使用标签。

所以,我不能使用getByRole 来测试它们。 为了在testing 中缓解这种情况,我尝试了一些解决方案,但我认为应该有更好的方法。这些是我建立的解决方案:

  1. 我已经 disabled eslint 并为此使用 documentQuerySecletor。
  /*eslint-disable */
  const activationCodeInputs = document.querySelectorAll('.codeItem input');
  expect(activationCodeInputs).toHaveLength(5);

  const systemIdTextarea = document.getElementById('systemId');
  expect(systemIdTextarea).not.toBeNull();
  /*eslint-enable */
  1. 另外,找到一篇使用data-testid的文章并将其传递给TextField viainputProps
// code
<TextField
 inputProps={{ 'data-testid': 'activationCode' }}
/>

 <TextField
  inputProps={{ 'data-testid': 'systemId' }}
 />

// tests
const activationCodeInputs = screen.getAllByTestId('activationCode');
expect(activationCodeInputs).toHaveLength(5);

const systemIdTextarea = screen.getByTestId('systemId');
expect(systemIdTextarea).toBeInTheDocument();

由于它只是一个常规元素 text field,我是否必须仅像文档中所说的第一个 preferred way 那样使用 getByRole 编写测试,是吗?

【问题讨论】:

  • 你的问题是什么?
  • @JohannesKlauß,你说得对,我已经更新了

标签: javascript reactjs jestjs material-ui react-testing-library


【解决方案1】:

对于 Material UI 和 React 测试,我刚刚在 Textfield 上使用了一个标签,并使用 getByLabelText 进行测试以获取带有该标签的输入

 <TextField
   label="input label"
   variant="outlined"
 />


screen.getByLabelText(/^input label/i)

【讨论】:

  • 在我的情况下,第一个限制是不要使用标签。
  • 您正在测试的组件上是否有多个文本字段?
  • 是的,我在问题中举了一些例子
【解决方案2】:

如果您没有与 TextField 关联的标签,并且列表中呈现了多个 TextField,则通过 testid 使用和查询就可以了。

如果您无法找到最佳选择器,您可以在测试中渲染组件后随时使用screen.logTestingPlaygroundURL()。这将为您提供测试库游乐场的 URL,您可以在其中检查渲染元素的最佳选择器。

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 2020-03-10
    • 2019-05-21
    • 1970-01-01
    • 2019-11-11
    • 2022-11-04
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多