1

Red, Red, Green, Refactor

 3 years ago
source link: https://dev.to/tyrw/red-red-green-refactor-n0h
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In this article, I describe a simple approach we use at Userfront to make our tests easier to write and less prone to error.

The classic: Red, Green, Refactor

In Test Driven Development, a common approach is "Red, Green, Refactor".

This is where we write failing test code (Red), then write application code to make it pass (Green). Then when we have the code working, we can refactor to make it look nicer, perform better, etc.

The abyss: a moving target

The problem with TDD is that it can be hard to get started and easy to forget about covering things.

For example, let's say we want to make an API call and parse the results.

Our test setup could look like:

it("should make an API call and parse the results", async () => {

});
Enter fullscreen modeExit fullscreen mode

But now... how do we start writing the actual test code?

In order to write the test code first, we have to have a very good idea of:

  • What we want to build
  • All the test suite's syntax and features
  • The libraries we'll use and how they work
  • Which functions to mock

This can be a moving target and is often a lot to keep in our head.

In software, keeping everything in your head leads to errors.

An extra Red

Our team has taken to using an "extra" failing step in the Red, Green, Refactor model to help get our tests started and to not miss things.

We write pseudo-tests that outline the process and give some idea of what tools we'll use and how to use them.

These "tests" are more like notes, but we add them to the actual test suite so that they fail where they're supposed to:

it("should make an API call and parse the response", async () => {
  expect("Make the API call with fetch").toEqual(true);
  expect("The mock webhook endpoint").toHaveBeenCalled();
  expect("The API response").toEqual({
    results: {},
    count: 5
  });
});
Enter fullscreen modeExit fullscreen mode

Note that these tests don't mean anything on their own. We don't expect this to pass:

expect("The mock webhook endpoint").toHaveBeenCalled();
Enter fullscreen modeExit fullscreen mode

This is only a shorthand note for later, but it lets us get the concept out of our head to free up capacity, and it keeps us from forgetting about it later.

We've found that this is a really nice pattern for simplifying the test-writing process.

It allows us to code with a clearer head and with less worry about whether we forgot something.

If you've ever felt overwhelmed writing tests, or missed something important because you forgot to cover it, consider Red, Red, Green, Refactor.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK