When testing user interactions in React components, like clicks or form submissions, we usually rely on tools like React Testing Library and Jest.
These tools help ensure our user interface works correctly when a user interacts with it.
First, let's understand what we're testing. Imagine we have a simple button in our React component that increments a counter every time it's clicked.
Here's a basic example of a React component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
To test this, we can use React Testing Library with Jest. Our goal is to simulate a click on the button and check if the counter increments.
Here's how we write the test:
import { render, screen, fireEvent } from '@testing-library/react';
import Counter from './Counter';
test('increments counter after button click', () => {
render(<Counter />);
const button = screen.getByText(/click me/i);
const counterText = screen.getByText(/you clicked 0 times/i);
fireEvent.click(button);
expect(counterText).toHaveTextContent('You clicked 1 time');
});
In this test, render sets up the component in a virtual DOM. screen.getByText fetches elements by their text content.
fireEvent.click simulates the click action, and expect checks the result.
It is Used for:
- E-commerce checkout page: Testing interactions like adding items to a cart and submitting payment info.
- Social media post creation: Ensuring form submissions for creating posts work properly.
- Online survey: Testing user answers submission.
- Interactive dashboards: Verifying that filters and buttons work when clicked.
Good testing helps catch problems early and gives users a smooth experience.