【问题标题】:How to write test cases for Select Box onChange Method in React Testing Library?如何为 React 测试库中的 Select Box onChange 方法编写测试用例?
【发布时间】:2021-12-30 05:19:42
【问题描述】:

我有一个选择框并将数据设置为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" />

【问题讨论】:

    标签: reactjs react-testing-library react-test-renderer react-testing


    【解决方案1】:

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

    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)
    })
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多