使用react测试库按角色测试材料ui TextField



我有一些组件,其中包括一些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并通过inputProps将其传递给TextField的文章
// 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,这是一个常规元素,所以我必须用getByRole编写测试吗?

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

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

screen.getByLabelText(/^input label/i)

如果没有与TextField关联的标签,并且在列表中呈现了多个TextFields,那么使用testid并通过testid进行查询就可以了。

如果您在找到最佳选择器时遇到困难,那么在测试中呈现组件后,可以始终使用screen.logTestingPlaygroundURL()。这将为您提供一个测试库游乐场的URL,在那里您可以检查渲染元素的最佳选择器。

最新更新