react的 Select组件 Input组件的 jest单元测试用例
以下是基本的单元测试用例:
Select组件:
- 测试Select组件是否能正确渲染出来
test('renders Select component correctly', () => {
const { getByTestId } = render(<Select />);
const selectElement = getByTestId('select');
expect(selectElement).toBeInTheDocument();
});
- 测试Select组件是否能正确显示选项
test('renders Select options correctly', () => {
const options = [
{ value: '1', label: 'Option 1' },
{ value: '2', label: 'Option 2' },
{ value: '3', label: 'Option 3' },
];
const { getByText } = render(<Select options={options} />);
options.forEach((option) => {
const optionElement = getByText(option.label);
expect(optionElement).toBeInTheDocument();
});
});
- 测试Select组件是否能正确触发onChange事件
test('onChange event is triggered correctly', () => {
const options = [
{ value: '1', label: 'Option 1' },
{ value: '2', label: 'Option 2' },
{ value: '3', label: 'Option 3' },
];
const handleChange = jest.fn();
const { getByTestId } = render(<Select options={options} onChange={handleChange} />);
const selectElement = getByTestId('select');
fireEvent.change(selectElement, { target: { value: '2' } });
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith('2');
});
Input组件:
- 测试Input组件是否能正确渲染出来
test('renders Input component correctly', () => {
const { getByTestId } = render(<Input />);
const inputElement = getByTestId('input');
expect(inputElement).toBeInTheDocument();
});
- 测试Input组件是否能正确显示placeholder
test('renders Input placeholder correctly', () => {
const placeholder = 'Enter text here';
const { getByPlaceholderText } = render(<Input placeholder={placeholder} />);
const inputElement = getByPlaceholderText(placeholder);
expect(inputElement).toBeInTheDocument();
});
- 测试Input组件是否能正确触发onChange事件
test('onChange event is triggered correctly', () => {
const handleChange = jest.fn();
const { getByTestId } = render(<Input onChange={handleChange} />);
const inputElement = getByTestId('input');
fireEvent.change(inputElement, { target: { value: 'hello world' } });
expect(handleChange).toHaveBeenCalledTimes(1);
expect(handleChange).toHaveBeenCalledWith('hello world');
});
``
原文地址: https://www.cveoy.top/t/topic/fuEO 著作权归作者所有。请勿转载和采集!