React Testing Best Practices in 2020

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

  1. getByRole – Most accessible
  2. getByLabelText – Form elements
  3. getByPlaceholderText
  4. getByText
  5. getByTestId – 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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.