【问题标题】:How do I trigger the change event on a react-select component with react-testing-library?如何使用 react-testing-library 在 react-select 组件上触发更改事件?
【发布时间】:2019-07-17 19:18:15
【问题描述】:

鉴于我无法直接使用react-testing-library 测试内部,我将如何测试使用react-select 的组件?例如,如果我有一个基于react-select 值的条件渲染,它不会渲染传统的<select/>,我还能触发更改吗?

import React, { useState } from "react";
import Select from "react-select";

const options = [
  { value: "First", label: "First" },
  { value: "Second", label: "Second" },
  { value: "Third", label: "Third" },
];

function TestApp() {
  const [option, setOption] = useState(null);
  return (
    <div>
      <label htmlFor="option-select">Select Option</label>
      <Select
        value={option}
        options={options}
        onChange={option => setOption(option)}
      />
      {option && <div>{option.label}</div>}
    </div>
  );
}

export default TestApp;

我什至不确定我应该查询什么。是隐藏输入吗?

【问题讨论】:

    标签: reactjs jestjs react-select react-hooks react-testing-library


    【解决方案1】:

    我的团队在我们的项目中有一个测试实用程序,可以让我们在花费太多时间试图弄清楚如何正确执行此操作后轻松选择一个项目。在这里分享,希望能帮助到其他人。

    这不依赖于任何 React Select 内部或模拟,但确实需要您设置一个 &lt;label&gt;,它有一个 for 链接到 React Select 输入。它使用标签来选择给定的选项值,就像用户在真实页面上一样。

    const KEY_DOWN = 40
    
    // Select an item from a React Select dropdown given a label and
    // choice label you wish to pick.
    export async function selectItem(
      container: HTMLElement,
      label: string,
      choice: string
    ): Promise<void> {
      // Focus and enable the dropdown of options.
      fireEvent.focus(getByLabelText(container, label))
      fireEvent.keyDown(getByLabelText(container, label), {
        keyCode: KEY_DOWN,
      })
    
      // Wait for the dropdown of options to be drawn.
      await findByText(container, choice)
    
      // Select the item we care about.
      fireEvent.click(getByText(container, choice))
    
      // Wait for your choice to be set as the input value.
      await findByDisplayValue(container, choice)
    }
    

    可以这样使用:

    it('selects an item', async () => {
      const { container } = render(<MyComponent/>)
    
      await selectItem(container, 'My label', 'value')
    })
    

    【讨论】:

    【解决方案2】:

    您可以尝试以下方法使其正常工作:

    1. 在 ReactSelect 组件 .react-select 输入元素上触发焦点事件。
    2. 在 .react-select__control 元素上触发 mouseDown 事件
    3. 点击您要选择的选项元素

    您可以添加值为“react-select”的 className 和 classNamePrefix 属性,以便专门选择您要测试的组件。

    PS:如果你仍然被困住,我鼓励你看看这个对话,上面的答案是从那里借来的 - https://spectrum.chat/react-testing-library/general/testing-react-select~5857bb70-b3b9-41a7-9991-83f782377581

    【讨论】:

    • 我看到@gpx 在那个线程中提到来模拟它。我不认为我曾经模拟过一个组件。效果一样吗?
    • 谢谢。我也在频谱上找到了this one,它有一个示例测试。 .
    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2019-08-29
    • 2021-02-23
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多