Clean Code

 Clean Code With Unit Tests

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: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:

Click

Post a Comment

0 Comments