← Impulso Blog

How do you know what to test in your application?

Knowing how to write tests is only half the battle when it comes to gaining confidence in your application. Knowing what to test is the other important half.

How to know what to test in your code

Editorial translation by Impulso.

Knowing how to test is important, and it’s a great skill to have. Kent has written several articles on the fundamentals of testing, how to set up tools, how to write tests for specific scenarios, and much more. But knowing how to write tests is only half the battle when it comes to gaining confidence in your application. Knowing what to test is the other important half.

In his workshop materials and on testingjavascript.com, Kent explains how to know what to test, but he still gets asked about it a lot. So he decided to tackle the topic in the article translated in this post.

A reminder of why we test

We write tests to feel confident that our application will work when users need it. Some people also write tests to improve their workflow, and that’s great, but lately I’ve been interested in confidence. In that case, we should choose what to test based on how much confidence it gives us. Here’s what I want you to keep in mind when you write tests:

Think less about the code you’re testing and more about the use cases your code supports.

When you think about the code itself, it’s easy and natural to start testing implementation details (which is a recipe for disaster).

Thinking in terms of use cases helps us write tests that reflect how users actually use the application.

The more your tests resemble the way your software is used, the more confidence they can give you. Kent C. Dodds 🧢 (@kentcdodds) March 23, 2018.

Code Coverage < Use Case Coverage

Code coverage is a metric that shows us which lines of code are executed during tests. Let’s use the code below as an example:

function arrayify(maybeArray) {
  if (Array.isArray(maybeArray)) {
    return maybeArray
  } else if (!maybeArray) {
    return []
  } else {
    return [maybeArray]
  }
}

Right now we don’t have any tests for this function, so our code coverage report shows 0% coverage for it. In this case, the report helps us see that tests are needed. But it doesn’t tell us what’s important about this function, or even what use cases it supports, which is the most important thing to keep in mind when writing tests.

In fact, when we look at an entire application and think about what to test, code coverage gives us very little guidance on where to spend our time.

A code coverage report helps us identify which parts of our codebase aren’t being tested. So when you look at a coverage report and find lines without tests, don’t think about if/else statements, loops, or lifecycles. Instead, ask yourself:

What use cases do these lines of code support, and what tests can I write to cover them?

Use Case Coverage tells us how many use cases our tests cover. Unfortunately, there’s nothing that automatically gives us a “Use Case Coverage” report. We have to do that ourselves. But a code coverage report can sometimes help us identify use cases we aren’t covering. Let’s give it a try.

If we read through the code and think about it for a minute, we can identify the first use case it supports: “It should return an array when given an array.” That use case makes a good title for our test.

test('retorne uma array se for fornecido uma array', () => {
  expect(arrayify(['Elephant', 'Giraffe'])).toEqual(['Elephant', 'Giraffe'])
})

With that test in place, our coverage report looks like this (the first 3 lines are covered):

function arrayify(maybeArray) {
  if (Array.isArray(maybeArray)) {
    return maybeArray
  } else if (!maybeArray) {
    return []
  } else {
    return [maybeArray]
  }
}

Now we can look at the remaining lines and see that there are two more use cases our test doesn’t cover yet:

  • Returns an empty array when given a falsy value.
  • Returns an array containing the given argument when it’s neither an array nor falsy.

Let’s add tests for those use cases and see how that affects code coverage.

test('retorne uma array vazia se for falso', () => {
  expect(arrayify()).toEqual([])
})

Great, almost there!

test(`retorne uma array com o argumento fornecido se o argumento não for uma array ou falso`, () => {
  expect(arrayify('Leopard')).toEqual(['Leopard'])
})

Nice! Now we can be confident that as long as we don’t need to change the use cases for this function, our tests will keep passing.

Code coverage isn’t a perfect metric, but it can help identify parts of our codebase that lack “use case coverage.”

Code coverage can hide missing use cases

Sometimes our code coverage report can show 100% coverage even when we don’t have 100% use case coverage. That’s why I sometimes try to think through all the use cases before I start writing tests.

For example, let’s imagine the function arrayify was implemented this way:

function arrayify(maybeArray) {
  if (Array.isArray(maybeArray)) {
    return maybeArray
  } else {
    return [maybeArray].filter(Boolean)
  }
}

In that case, we can get 100% code coverage with the following two cases:

  • Returns an array when given an array.
  • Returns an array when the given argument isn’t an array.

But if we could look at a use case coverage report, we’d see that we’re missing one use case:

  • Returns an empty array when given a falsy value.

That could be a problem, because our tests don’t give us much confidence that our code will work when users use it like this: arrayify(). It’s fine for now because our code supports this use case even though we don’t have a test for it. But the reason we have tests is to make sure the code keeps supporting its use cases even when things change.

Here’s how missing that test could go wrong. Someone might see this code.filter(Boolean) and think: “Hmm, that’s weird… Do we really need that?”Then they remove it, and our tests keep passing. But any code that relied on how falsy values were handled will break.

Remember: Test use cases, not code.

How does this apply to React?

Front-end testing can differ a bit from back-end testing in practice, though the same principle applies.

Moving on…

When you’re writing code, remember that you have two kinds of users to support: End users and developers. Again, if you think about the code instead of the use cases, it’s easy to fall into the trap of testing implementation details. When you do that, your code gains a third user.

There are some aspects of React that people think they should test, and they end up testing implementation details. In each of these cases, think about the observable effect the code has for end users and developers. That’s your use case. Test it.

  • Lifecycle methods
  • Elements’ event handlers
  • Internal component state

On the other hand, here are some things you should test because they serve both kinds of users. Each of these can change the DOM, make HTTP requests, invoke a callback, or trigger other observable side effects that can be useful in a test.

  • User interaction (using fireEvent from React Testing Library): Can the end user interact with the element this component renders?
  • Changing props (using rerender from React Testing Library): What happens when a developer rerenders your component with new props?
  • Changing context (using rerender from React Testing Library): What happens when a developer changes the context by rerendering your component?
  • Subscription changes: What happens when an event emitter changes something your component subscribes to? (For example, Firebase, a Redux store, a route, a media query, or a DOM-based subscription such as online status.)

How do I know where to start with an application?

So we know how to think about “what to test” for individual components and even pages in your application, but where do we start? It can be a little stressful, especially if you’re starting to test a large application.

So look at the application from the user’s point of view and ask:

Which part of this application would I be most upset about if it weren’t working?

Or, as it’s more commonly put:

What would be the worst thing to break in this application?

I recommend making a list of the features your application supports and prioritizing them based on those criteria. It’s a great exercise to do with your team and manager. The meeting can have a side effect: it can help everyone in the room understand why testing matters, and it might even convince them to prioritize testing for every other feature they build.

Once you have a prioritized list, I suggest writing an end-to-end (E2E) test to cover the “happy path” most users take in a given scenario. You can usually cover most of the features on your list this way. It can take a little time to set up, but it’ll yield a BIG financial return.

E2E tests won’t give you 100% use case coverage (and you shouldn’t try for 100%), much less 100% code coverage (and you shouldn’t worry about that in E2E tests either). But they’ll give you a great starting point and a lot more confidence.

Once you have a few E2E tests, you can start writing integration tests for cases your E2E tests miss, as well as unit tests for the more complex business logic those features use. From there, you’ll add tests over time. Don’t worry about reaching 100% code coverage. It’s not worth it.

➕ To establish a testing culture and set reasonable code coverage goals, I suggest watching Aaron Abramov ’s talk, Establishing testing patterns with software design principles

📚 Read more about the differences between the types of tests here: Static vs Unit vs Integration vs E2E Testing for Frontend Apps

Conclusion

With enough time and experience, you’ll develop an intuition for what to test. You’ll probably make mistakes and struggle a little. Don’t give up! Keep going. Good luck.

💡 This post is a translation of “How to know what to test”by Kent C. Dodds.

Related articles