Testing React applications has evolved. Here are the best practices I’ve learned for writing maintainable, effective tests in 2020.
Use React Testing Library
Enzyme is out, React Testing Library is in. Test behavior, not implementation.
import { render, screen, fireEvent } from '@testing-library/react';
test('submits form with user data', async () => {
const onSubmit = jest.fn();
render(<UserForm onSubmit={onSubmit} />);
// Query by accessible role/label
fireEvent.change(screen.getByLabelText(/email/i), {
target: { value: 'test@example.com' }
});
fireEvent.click(screen.getByRole('button', { name: /submit/i }));
expect(onSubmit).toHaveBeenCalledWith({
email: 'test@example.com'
});
});
Query Priority
getByRole– Most accessiblegetByLabelText– Form elementsgetByPlaceholderTextgetByTextgetByTestId– Last resort
Avoid These
- Testing implementation details (state, props)
- Shallow rendering (usually)
- Snapshot tests for complex components
- Testing third-party libraries
References
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.