How do I trigger the change event on a react-select component with react-testing-library?

时间:2019-02-24 03:13:37

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

Given that I can't test internals directly with react-testing-library, how would I go about testing a component that uses react-select? For instance, if I have a conditional render based on the value of the react-select, which doesn't render a traditional <select/>, can I still trigger the change?

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;

I'm not even sure what I should query for. Is it the hidden input?

2 个答案:

答案 0 :(得分:3)

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

这不依赖任何React Select内部或模拟,但确实需要您设置一个<label>,其中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')
})

答案 1 :(得分:1)

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

  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