react-select - 如何将 data-testid 属性添加到 react-select 组件
问题描述
使用 react-testing-library,我希望测试在 React 中实现的表单。
该表单包含一个 react-select 类型的 React 组件。
需要单击 react-select 组件中没有标签、没有文本等的部分(例如下拉箭头)。
通常,react-testing-library 执行此操作的方法是向相关项目添加“data-testid”属性。
我发现可以通过向 react-select 组件提供 'classNamePrefix' 属性来为 react-select 的每个部分赋予一个 CSS 类属性。有没有办法对 data-testid 属性做同样的事情?
注意:我知道我可以提供 react-select 组件的自定义实现,但是获得一个属性似乎有点矫枉过正。
解决方案
首先,我会质疑为什么没有标签,Select
因为这不会被归类为屏幕阅读器可以访问。
但是,如果你不想要一个可见的标签,你总是可以将一个aria-label
道具传递给Select
并使用 getByLabelText 以这种方式进行测试。
<Select aria-label="Example Label" ... />
getByLabelText('Example Label')
如果您确实需要添加 adata-testid
您可以替换您想要添加的特定组件data-testid
并添加它。(有关更多信息,请参阅文档)
例如
// @flow
import React from 'react';
import EmojiIcon from '@atlaskit/icon/glyph/emoji';
import Select, { components } from 'react-select';
import { colourOptions } from './docs/data';
const DropdownIndicator = props => {
return (
<components.DropdownIndicator {...props}>
<span data-testid="DropdownIndicator">
<EmojiIcon primaryColor={colourOptions[2].color} />
</span>
</components.DropdownIndicator>
);
};
export default () => (
<Select
closeMenuOnSelect={false}
components={{ DropdownIndicator }}
defaultValue={[colourOptions[4], colourOptions[5]]}
isMulti
options={colourOptions}
/>
);
推荐阅读
- c# - C# Skype Bot 下载附件
- vaadin - 这段代码有什么问题?它抛出空错误
- r - 在 R 中使用访问器“[”时,在数据帧上使用时的默认行为是什么?
- go - 为什么我在 go lang 的类型断言上得到奇怪的结果?
- flutter - 重置提供者数据 - Flutter
- django - 身份验证模型用户在管理员中的 Django 导入导出
- node.js - 没有端口的快速访问应用程序
- kubernetes - 拥有不同版本的 AKS 集群和节点池 Kubernetes 版本有什么缺点?
- scala - org.apache.orc.impl.SchemaEvolution$IllegalEvolutionException: ORC 不支持从文件类型 char(6) (12) 到 reader 的类型转换
- r - 将字符向量转换为 R 中的单行数据框