Member-only story
Clean Code With Unit Tests
Tips and tricks for keeping your test suites clean
Unit tests are important. They prevent regressions as you refactor code, serve as documentation, and save you hours of time not spent doing tedious manual testing. In short, tests enable change.
But how much attention to cleanliness do we give our tests? We refactor our app’s production code, give descriptive names to variables, extract methods for repeatable functionality, and make our code easy to reason about. But do we do the same for our tests?
Consider this quote from Robert C. Martin:
“Test code is just as important as production code. It is not a second-class citizen. It requires thought, design, and care. It must be kept as clean as production code.”
So, how do we keep our test code clean? Let’s consider some ideas below.
Structuring Tests
Tests should be structured according to the Arrange-Act-Assert pattern. This pattern goes by many names and is sometimes referred to as the Build-Operate-Check, Setup-Exercise-Verify, or Given-When-Then pattern.
I prefer Arrange-Act-Assert for the alluring alliteration. Regardless of what you call it, the pattern looks like this:
- Arrange: Set up the test fixtures, objects, or components you’ll be working with.
- Act: Perform some operation, perhaps by calling a function or clicking a button.
- Assert: Assert that the expected behavior or output occurred.
In the React world, applying this pattern when testing a simple toggle button component might look like this:

We arrange our code and act on it all in the same line by rendering the ToggleButton
component. We then make assertions on the output that it renders a button to the DOM and that the button’s text is visible on the screen.