Reactjs 如何使用react测试库选择测试react

Reactjs 如何使用react测试库选择测试react,reactjs,integration-testing,react-select,react-testing-library,Reactjs,Integration Testing,React Select,React Testing Library,App.js import React,{Component}来自“React”; 从“反应选择”导入选择; const SELECT_OPTIONS=[“FOO”,“BAR”].map(e=>{ 返回{value:e,label:e}; }); 类应用程序扩展组件{ 状态={ 已选择:选择选项[0]。值 }; handleSelectChange=e=>{ this.setState({selected:e.value}); }; render(){ const{selected}=this.

App.js

import React,{Component}来自“React”;
从“反应选择”导入选择;
const SELECT_OPTIONS=[“FOO”,“BAR”].map(e=>{
返回{value:e,label:e};
});
类应用程序扩展组件{
状态={
已选择:选择选项[0]。值
};
handleSelectChange=e=>{
this.setState({selected:e.value});
};
render(){
const{selected}=this.state;
常量值={value:selected,label:selected};
返回(

{selected}

); } } 导出默认应用程序;
App.test.js

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

const SELECT_OPTIONS = ["FOO", "BAR"].map(e => {
  return { value: e, label: e };
});

class App extends Component {
  state = {
    selected: SELECT_OPTIONS[0].value
  };

  handleSelectChange = e => {
    this.setState({ selected: e.value });
  };

  render() {
    const { selected } = this.state;
    const value = { value: selected, label: selected };
    return (
      <div className="App">
        <div data-testid="select">
          <Select
            multi={false}
            value={value}
            options={SELECT_OPTIONS}
            onChange={this.handleSelectChange}
          />
        </div>
        <p data-testid="select-output">{selected}</p>
      </div>
    );
  }
}

export default App;
从“React”导入React;
进口{
提供,
fireEvent,
清理,,
waitForElement,
getByText
}来自“反应测试库”;
从“/App”导入应用程序;
每次之后(清理);
常量设置=()=>{
const utils=render();
const selectOutput=utils.getByTestId(“选择输出”);
const selectInput=document.getElementById(“react-select-2-input”);
返回{selectOutput,selectInput};
};
测试(“它可以更改所选项目”,异步()=>{
const{selectOutput,selectInput}=setup();
getByText(选择输出,“FOO”);
change(selectInput,{target:{value:“BAR”});
等待waitForElement(()=>getByText(选择Output,“BAR”);
});

这个最小的示例在浏览器中按预期工作,但测试失败。我认为中的onChange处理程序没有被调用。如何在测试中触发onChange回调?查找fireEvent所在元素的首选方法是什么?谢谢

这是关于RTL:D的最常被问到的问题

最好的策略是使用(或测试框架中的等效工具)模拟select并呈现一个HTML select

关于为什么这是最好的方法的更多信息,我写了一些同样适用于这个案例的东西。OP询问了一个选择材料界面,但想法是一样的

我的回答是:

因为您无法控制该UI。它在第三方模块中定义

因此,您有两种选择:

您可以找出材质库创建的HTML,然后使用container.querySelector查找其元素并与之交互。这需要一段时间,但应该是可能的。在完成所有这些之后,您必须希望在每个新版本中,它们不会对DOM结构进行太多更改,否则您可能需要更新所有测试

另一个选择是相信Material UI将生成一个可以工作并且用户可以使用的组件。基于这种信任,您可以简单地将测试中的组件替换为更简单的组件

是的,选项一测试用户看到的东西,但选项二更容易维护

根据我的经验,第二个选项很好,但是当然,您的用例可能不同,您可能需要测试实际的组件

这是一个如何模拟选择的示例:

import React from "react";
import {
  render,
  fireEvent,
  cleanup,
  waitForElement,
  getByText
} from "react-testing-library";
import App from "./App";

afterEach(cleanup);

const setup = () => {
  const utils = render(<App />);
  const selectOutput = utils.getByTestId("select-output");
  const selectInput = document.getElementById("react-select-2-input");
  return { selectOutput, selectInput };
};

test("it can change selected item", async () => {
  const { selectOutput, selectInput } = setup();
  getByText(selectOutput, "FOO");
  fireEvent.change(selectInput, { target: { value: "BAR" } });
  await waitForElement(() => getByText(selectOutput, "BAR"));
});
jest.mock(“react-select”,()=>({options,value,onChange})=>{
函数句柄更改(事件){
const option=options.find(
option=>option.value==event.currentTarget.value
);
onChange(选项);
}
返回(
{options.map({label,value})=>(
{label}
))}
);
});

您可以阅读更多内容。

在我的项目中,我正在使用react测试库和jest dom。 我遇到了同样的问题-经过一些调查,我找到了基于线程的解决方案:

请注意,render的顶级函数以及各个步骤都必须是异步的

在这种情况下不需要使用焦点事件,它将允许选择多个值

此外,getSelectItem内部必须有异步回调

jest.mock("react-select", () => ({ options, value, onChange }) => {
  function handleChange(event) {
    const option = options.find(
      option => option.value === event.currentTarget.value
    );
    onChange(option);
  }
  return (
    <select data-testid="select" value={value} onChange={handleChange}>
      {options.map(({ label, value }) => (
        <option key={value} value={value}>
          {label}
        </option>
      ))}
    </select>
  );
});
const DOWN_ARROW={keyCode:40};
它('可以填充渲染和值,然后提交',async()=>{
常数{
作为碎片,
getByLabelText,
getByText,
}=render();
( ... )
//功能
常量getSelectItem=(getByLabelText,getByText)=>async(selectLabel,itemText)=>{
fireEvent.keyDown(getByLabelText(selectLabel),向下箭头);
等待waitForElement(()=>getByText(itemText));
单击(getByText(itemText));
}
//用法
const selectItem=getSelectItem(getByLabelText,getByText);
等待selectItem(“标签”、“选项”);
( ... )
}

与@momimo的答案类似,我编写了一个小助手,从TypeScript中的
react select
中选择一个选项

帮助文件:

从'@testing library/react'导入{getByText,findByText,firevent};
常数keyDownEvent={
键:“箭头向下”,
};
导出异步函数selectOption(容器:HTMLElement,optionText:string){
常量占位符=getByText(容器“选择…”);
fireEvent.keyDown(占位符,keyDownEvent);
等待findByText(容器、optionText);
单击(getByText(容器,optionText));
}
用法:

const DOWN_ARROW = { keyCode: 40 };

it('renders and values can be filled then submitted', async () => {
  const {
    asFragment,
    getByLabelText,
    getByText,
  } = render(<MyComponent />);

  ( ... )

  // the function
  const getSelectItem = (getByLabelText, getByText) => async (selectLabel, itemText) => {
    fireEvent.keyDown(getByLabelText(selectLabel), DOWN_ARROW);
    await waitForElement(() => getByText(itemText));
    fireEvent.click(getByText(itemText));
  }

  // usage
  const selectItem = getSelectItem(getByLabelText, getByText);

  await selectItem('Label', 'Option');

  ( ... )

}
导出常量MyComponent:React.FunctionComponent=()=>{ 返回( ); };
it('可以选择选项',异步()=>{
const{getByTestId}=render();
//打开反应选择选项,然后单击“星期一”。
等待selectOption(getByTestId('day-selector')、'Monday');
});
注:
container:container for select box(例如:container=getByTestId('seclectTestId'))

最后,有一个库可以帮助我们做到这一点:。适用于单选或多选:

@测试库/react
文档:

export async function selectOption(container: HTMLElement, optionText: string) {
  let listControl: any = '';
  await waitForElement(
    () => (listControl = container.querySelector('.Select-control')),
  );
  fireEvent.mouseDown(listControl);
  await wait();
  const option = getByText(container, optionText);
  fireEvent.mouseDown(option);
  await wait();
}
从“React”导入React
从“反应选择”导入选择
从'@testing library/react'导入{render}
从“反应选择事件”导入selectEvent
常量{getByTestId,GetByBelText}=render(
食物
)
expect(getByTestId('form')).toHaveFormValues({food:'})//空选择
//选择两个值。。。
等待selectEvent.select(getByLabelText(“食物”),[“草莓”、“芒果”)
经验
export async function selectOption(container: HTMLElement, optionText: string) {
  let listControl: any = '';
  await waitForElement(
    () => (listControl = container.querySelector('.Select-control')),
  );
  fireEvent.mouseDown(listControl);
  await wait();
  const option = getByText(container, optionText);
  fireEvent.mouseDown(option);
  await wait();
}
import React from 'react'
import Select from 'react-select'
import { render } from '@testing-library/react'
import selectEvent from 'react-select-event'

const { getByTestId, getByLabelText } = render(
  <form data-testid="form">
    <label htmlFor="food">Food</label>
    <Select options={OPTIONS} name="food" inputId="food" isMulti />
  </form>
)
expect(getByTestId('form')).toHaveFormValues({ food: '' }) // empty select

// select two values...
await selectEvent.select(getByLabelText('Food'), ['Strawberry', 'Mango'])
expect(getByTestId('form')).toHaveFormValues({ food: ['strawberry', 'mango'] })

// ...and add a third one
await selectEvent.select(getByLabelText('Food'), 'Chocolate')
expect(getByTestId('form')).toHaveFormValues({
  food: ['strawberry', 'mango', 'chocolate'],
})
fireEvent.change(getByTestId("select-test-id"), { target: { value: "1" } });
const select = screen.container.querySelector(
  "input[name='select']"
);

selectEvent.select(select, "Value");