javascript / intermediate
Snippet
Testing Asynchronous Form Submissions with User-Event and FindBy Queries
Testing Library's userEvent simulates real browser events asynchronously, including focus, keystrokes, and click propagation. Using async/await alongside findBy queries ensures tests reliably wait for DOM updates triggered by resolved promises or state transitions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { FeedbackForm } from './FeedbackForm';test('submits feedback comment and displays confirmation message', async () => {const user = userEvent.setup();const mockOnSubmit = jest.fn().mockResolvedValue({ status: 'ok' });render(<FeedbackForm onSubmit={mockOnSubmit} />);const inputField = screen.getByRole('textbox', { name: /feedback/i });const submitButton = screen.getByRole('button', { name: /send/i });await user.type(inputField, 'Great developer experience!');await user.click(submitButton);expect(mockOnSubmit).toHaveBeenCalledWith('Great developer experience!');const confirmation = await screen.findByText(/thank you for your feedback/i);expect(confirmation).toBeInTheDocument();});
react
Breakdown
1
const user = userEvent.setup();
Initializes the user-event session instance before executing realistic simulated browser actions.
2
await user.type(inputField, 'Great developer experience!');
Asynchronously simulates individual character keydowns, input events, and state mutations.
3
expect(mockOnSubmit).toHaveBeenCalledWith('Great developer experience!');
Asserts the callback received the fully typed state payload on form submission.
4
const confirmation = await screen.findByText(/thank you for your feedback/i);
Polls the DOM asynchronously until the success message appears after state updates complete.