首页 > 解决方案 > 如何将 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 组件的自定义实现,但是获得一个属性似乎有点矫枉过正。

标签: react-selectreact-testing-library

解决方案


首先,我会质疑为什么没有标签,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}
  />
);

代码沙盒链接


推荐阅读