【发布时间】:2021-06-28 12:38:14
【问题描述】:
我有一些组件,其中包括一些mui TextFields,我的组件有两种情况:
-
一个
TextField是为LicenseCode 设计的,它不能有标签。 -
还有一些
TextFields将通过map函数创建,我也不能为它们中的每一个使用标签。
所以,我不能使用getByRole 来测试它们。
为了在testing 中缓解这种情况,我尝试了一些解决方案,但我认为应该有更好的方法。这些是我建立的解决方案:
- 我已经
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 */
- 另外,找到一篇使用
data-testid的文章并将其传递给TextFieldviainputProps
// 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