It is common to say that unit tests are documentation. I've always hated that saying, because people seem to use it to avoid writing tutorials or other documentation.

However, I eventually conceded that tests can be documentation for specific methods, even if they don't teach people how to use your code or software. They do give insight into what the code was written for and what the author was thinking about the primary cases and edge cases.

However, tests need to be named properly to achieve this result and I find test naming to be inconsistent. As such, I'd like to show you how I like to name and group tests.

The Suites

When building TypeScript applications, I often have classes with methods on them. So, first I'll create two nested test suites. The other suite has the class name, and the inner suite has the method name:

view plain print about
1describe('className', () => {
2describe('methodName()', () => {
3})
4})

All my tests for this method go in the method name describe block.

Naming the Test

I need to write a bunch of tests for the method in question. I like to name the tests using an approach like this: Should see result when action is taken with condition(s) There are three parts of this:

  • Should: This defines the expected result.
  • When: This defines the action that is taken.
  • With: Defines the conditions on the action.

Here are a few examples:

  • Should load product data when route is loaded with an ID
  • Should redirect to search screen when route is loaded with no ID
  • Should return Spanish product title when title is requested with user's localization settings are set to Spanish
  • Should return English title when title is requested with user's localization settings set to Spanish and a product with no Spanish title

The point of this is that I want my tests to have descriptive, consistent titles. This approach makes it super easy to understand the purpose of the test.

I want to easily understand what the test is doing, what the results are and this helps.