Testing
Quality and maintenance
10-15 min
Testing in React
Tests are essential for ensuring the quality and maintainability of your React applications. We'll explore the different types of tests and the tools available.
Basic setup
Create React App already includes Jest and React Testing Library. For existing projects:
npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event
Unit tests
Testing a simple component
// Button.js
function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
}
// Button.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('rendre le bouton avec le bon texte', () => {
render(<Button>Cliquez-moi</Button>);
expect(screen.getByText('Cliquez-moi')).toBeInTheDocument();
});
test('appeler onClick quand le bouton est cliqué', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Cliquez-moi</Button>);
fireEvent.click(screen.getByText('Cliquez-moi'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion