以下是基本的单元测试用例:

Select 组件

  1. 测试 Select 组件是否能正确渲染出来
test('renders Select component correctly', () => {
  const { getByTestId } = render(<Select />); 
  const selectElement = getByTestId('select');
  expect(selectElement).toBeInTheDocument();
});
  1. 测试 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();
  });
});
  1. 测试 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 组件

  1. 测试 Input 组件是否能正确渲染出来
test('renders Input component correctly', () => {
  const { getByTestId } = render(<Input />);
  const inputElement = getByTestId('input');
  expect(inputElement).toBeInTheDocument();
});
  1. 测试 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();
});
  1. 测试 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');
});
React Select 和 Input 组件的 Jest 单元测试用例