我有一个普通的选择列表。当我选择一个选项时,我需要测试 handleChoice 被调用。我如何使用 React 测试库来做到这一点?
<select
onChange={handleChoice}
data-testid="select"
>
<option value="default">Make your choice</option>
{attributes.map(item => {
return (
<option key={item.key} value={item.key}>
{item.label}
</option>
);
})}
</select>
getByDisplayValue
值为 item.label
不返回任何东西,也许这是因为它在页面上不可见?
最佳答案
添加 data-testid
到选项
<option data-testid="select-option" key={item.key} value={item.key}>
{item.label}
</option>
然后,在测试中调用 fireEvent.change
, 通过 getAllByTestId
获取所有选项并检查所选选项:import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import App from './App';
test('Simulates selection', () => {
const { getByTestId, getAllByTestId } = render(<App />);
//The value should be the key of the option
fireEvent.change(getByTestId('select'), { target: { value: 2 } })
let options = getAllByTestId('select-option')
expect(options[0].selected).toBeFalsy();
expect(options[1].selected).toBeTruthy();
expect(options[2].selected).toBeFalsy();
//...
})
对于您的问题,getByDisplayValue
仅适用于显示的值
关于react-testing-library - 如何使用 React 测试库从选择列表中选择一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946870/