DEV Community

Robert Prib
Robert Prib

Posted on

How our team writes React tests and other stuff too 5 June 2021 8 minute read

Have you ever worked in a codebase where each test file was different to the next? Different terminology and grouping of test scenarios; different usages of snapshot testing and react-testing-library.

The effect of this meant wasted time reading a full test file to understand its structure before adding another test case. Creating new tests involved making multiple decisions; should I copy the structure of an existing test or create a new one? Should I use snapshot tests?

We solved this problem by defining guidelines to follow, that make writing tests that are easy to read and write, and would reduced wasted time on decisions.

Our guidelines are as follows:

  • Group tests by render and user behaviours
  • Use a snapshot test to validate render
  • Use GIVEN-WHEN-THEN to describe branching logic
  • Don't be afraid to stub child components
  • Don't re-test functionality of other components
  • Use a single expect statement per test
  • Accept unit testing UI components can be difficult
  • Try use screen.getByRole
  • Isolate complex component logic, and test separately

For full detail on our approach and each guideline for writing tests see https://whassup.github.io/blog/article/how-our-team-writes-tests

Top comments (0)