1

我有一个选择框并将数据设置为onChange事件的状态。请看下面的代码。任何人都可以帮助我在 React 测试库中为此onChange事件编写案例。

const [optionValue, setOptionValue] = useState({ value: '', label: '' })

const handleOnChange = (option: OptionType): void => setOptionValue(option)

<Select name={title} id={title} placeholder="Choose an Option" options={setOptionsData} defaultOption={optionValue} onChange={e => { handleOnChange(e) }} data-test="options" />

4

1 回答 1

0

我建议使用作为 React 测试库生态系统一部分的userEvent 。它允许您编写更接近真实用户行为的测试。例子:**

it('should correctly set default option', () => {
  render(<App />)
  expect(screen.getByRole('option', {name: 'Make a choice'}).selected).toBe(true)
})


it('should allow user to change country', () => {
  render(<App />)
  userEvent.selectOptions(
    // Find the select element
    screen.getByRole('combobox'),
    // Find and select the Ireland option
    screen.getByRole('option', {name: 'Ireland'}),
  )
  expect(screen.getByRole('option', {name: 'Ireland'}).selected).toBe(true)
})

查看这篇文章(我自己写的)以获取有关如何使用 React 测试库测试选择元素的更多信息。

于 2021-12-09T01:17:25.277 回答