如何用React Testing Library测试Material-UI useAutocomplete的onChange事件
useAutocomplete's onChange with React Testing Library is Absolutely Feasible! The empty groupedOptions issue you’re seeing in tests is easy to fix by setting up proper mock data and replicating real user interactions. Here’s a step-by-step guide to test your onChange logic and get full code coverage:
1. Mock Dependencies & Test Data
First, create mock route data to populate groupedOptions, and mock your state setters to track their calls:
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import YourAutocompleteComponent from './YourAutocompleteComponent'; // Mock route data to populate suggestions const mockRoutes = [ { routeName: 'Downtown Loop', routeId: 'RT-001' }, { routeName: 'Uptown Express', routeId: 'RT-002' } ]; // Mock state setters to verify their behavior const mockSetPreviousRoute = jest.fn(); const mockSetSelectedRoute = jest.fn();
2. Write Test Cases for onChange
Test 1: Selecting an Option
This tests the scenario where a user picks a suggestion from the list:
describe('Autocomplete Component', () => { beforeEach(() => { jest.clearAllMocks(); // Reset mocks between tests }); it('updates route state when selecting a suggestion', async () => { const initialSelectedRoute = { routeName: 'Old Route', routeId: 'RT-000' }; // Render component with mock props render( <YourAutocompleteComponent routeInformation={mockRoutes} setPreviousRoute={mockSetPreviousRoute} setSelectedRoute={mockSetSelectedRoute} selectedRoute={initialSelectedRoute} /> ); // Type into the input to trigger suggestions const searchInput = screen.getByTestId('SearchInput'); await userEvent.type(searchInput, 'Downtown'); // Wait for the suggestion to appear and click it const targetSuggestion = await screen.findByText('Downtown Loop | ID: RT-001'); await userEvent.click(targetSuggestion); // Verify onChange logic ran correctly expect(mockSetPreviousRoute).toHaveBeenCalledWith(initialSelectedRoute); expect(mockSetSelectedRoute).toHaveBeenCalledWith(mockRoutes[0]); });
Test 2: Clearing the Input
This tests the case where the user clicks the clear button:
it('resets selected route when clearing the input', async () => { const initialSelectedRoute = mockRoutes[0]; render( <YourAutocompleteComponent routeInformation={mockRoutes} setPreviousRoute={mockSetPreviousRoute} setSelectedRoute={mockSetSelectedRoute} selectedRoute={initialSelectedRoute} /> ); // Click the clear button const clearButton = screen.getByRole('button', { name: /cancel/i }); await userEvent.click(clearButton); // Verify clear logic executed expect(mockSetPreviousRoute).toHaveBeenCalledWith(initialSelectedRoute); expect(mockSetSelectedRoute).toHaveBeenCalledWith(undefined); }); });
3. Fixing Empty groupedOptions in Tests
Your groupedOptions was empty because you weren’t passing mock routeInformation to the component during testing. By providing mockRoutes as the routeInformation prop, useAutocomplete will generate populated groupedOptions, allowing you to interact with the suggestion list.
Bonus: Cover Edge Cases
To get full coverage, add tests for:
- Empty route data: Render the component with
routeInformation={[]}and verify no suggestions appear. - Escape key clear: Type into the input, press Escape, and confirm
setSelectedRouteis called withundefined.
内容的提问来源于stack exchange,提问作者prudhvi

