简体   繁体   English

在 React 测试库中设置下拉列表的值

[英]Set a dropdown's value in React Testing Library

For testing an input it works like this:为了测试输入,它的工作方式如下:

  it('test input', () => {
    const { getByTestId, getByLabelText } = render(<MyComponent />);

    const myButton = getByTestId('submit-button');
    expect(myButton).toBeInTheDocument();

    fireEvent.change(getByLabelText('first-name'), {
      target: { value: 'ted' }
    });

    // do something
  });

the above test is setting the value of first-name input to "ted" and moves forward.上面的测试是将first-name输入的值设置为“ted”并继续前进。

I want to do something similar but for a drop-down selector.我想做类似的事情,但要使用下拉选择器。

This is the component:这是组件:

<SelectInput
  label='my-dropdown'
  onChange={onChange}
  options={myOptions}
/>;

myOptions is an array of this shape: myOptions是这个形状的数组:

const myOptions = [
  { id: '0', name: 'zero' },
  { id: '1', name: 'one' },
  { id: '2', name: 'two' }
];

it works fine in the application, no errors from this part.它在应用程序中运行良好,这部分没有错误。

Here comes the testing of it, I did something but it doesn't work:这是对它的测试,我做了一些但它不起作用:

  it('test dropdpwn', () => {
    const { getByTestId, getByLabelText } = render(<MyComponent />);

    const saveButton = getByTestId('submit-button');
    expect(saveButton).toBeInTheDocument();

    fireEvent.change(getByLabelText('my-dropdown'), {
      target: { value: { id: '0', name: 'zero' } }
    });

    // do something
  });

the above code doesn't work, it doesn't set the dropdown with that value.上面的代码不起作用,它没有使用该值设置下拉列表。

Any ideas on how to solve this?关于如何解决这个问题的任何想法? Not sure if it's important, but all those inputs are inside a react-hook-form and at the end it should test that the onSubmit is working (it works only if all inputs are set).不确定它是否重要,但所有这些输入都在 react-hook-form 内,最后它应该测试 onSubmit 是否正常工作(只有在设置了所有输入时才有效)。

You can try using userEvent.selectOptions , it should work.您可以尝试使用userEvent.selectOptions ,它应该可以工作。

I'm assuming that <option> takes the name as its value.我假设<option>name作为其值。

  it('test dropdpwn', () => {
    const { getByTestId, getByLabelText } = render(<MyComponent />);

    const saveButton = getByTestId('submit-button');
    expect(saveButton).toBeInTheDocument();

    userEvent.selectOptions(getByLabelText('my-dropdown'), 'zero')

    // do something
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM