javascript / intermediate
Snippet
Testing React Component Form Submission using Jest Mock Spies
Unit testing interactive form components requires verifying that event handlers correctly parse user inputs and dispatch payloads via callback props. Jest mock functions (`jest.fn()`) act as spies to record call counts, execution arguments, and invocations. Using `expect.objectContaining()` allows asserting the presence of specific payload properties while ignoring non-deterministic values like timestamps.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { render, screen, fireEvent } from '@testing-library/react';function FeedbackForm({ onSubmitFeedback }) {const [comment, setComment] = React.useState('');const handleSubmit = (e) => {e.preventDefault();if (comment.trim().length > 0) {onSubmitFeedback({ text: comment, timestamp: Date.now() });setComment('');}};return (<form onSubmit={handleSubmit}><inputaria-label="comment-input"value={comment}onChange={(e) => setComment(e.target.value)}/><button type="submit">Submit</button></form>);}test('calls onSubmitFeedback callback with expected structure on submit', () => {const handleSubmitMock = jest.fn();render(<FeedbackForm onSubmitFeedback={handleSubmitMock} />);const input = screen.getByLabelText('comment-input');fireEvent.change(input, { target: { value: 'Great feature!' } });fireEvent.click(screen.getByRole('button', { name: /submit/i }));expect(handleSubmitMock).toHaveBeenCalledTimes(1);expect(handleSubmitMock).toHaveBeenCalledWith(expect.objectContaining({ text: 'Great feature!' }));});
react
Breakdown
1
const handleSubmitMock = jest.fn();
Instantiates a mock spy function to track and assert callback invocations.
2
fireEvent.change(input, { target: { value: 'Great feature!' } });
Simulates a user typing into the controlled form text field.
3
expect(handleSubmitMock).toHaveBeenCalledWith(expect.objectContaining({ text: 'Great feature!' }));
Verifies that the mock was called with an object containing the expected input text payload.