This content originally appeared on DEV Community and was authored by Tyler Warnock
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 () => {
});
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
});
});
Note that these tests don't mean anything on their own. We don't expect this to pass:
expect("The mock webhook endpoint").toHaveBeenCalled();
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.
This content originally appeared on DEV Community and was authored by Tyler Warnock
Tyler Warnock | Sciencx (2021-06-28T18:23:54+00:00) Red, Red, Green, Refactor. Retrieved from https://www.scien.cx/2021/06/28/red-red-green-refactor/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.