One of the biggest roadblocks I've personally run into in testing JavaScript—the thing that grinds my testing process to a halt—is fretting over implementation details and code coverage. Today, I wanted to talk about why they don't matter. Let's dig in! This article is part of an ongoing series of JavaScript testing. In past articles, we looked at buildless testing, an overview of testing approaches, how to write unit tests, how to organize tests, and TDD. An example of an implementation detailLooking at the
Let's imagine that we wanted to make sure that if someone passed in a non-numeric value, the script didn't break…
Under the hood, we might try to use We might also add a
Now, if we pass in numeric strings, they get converted to numbers, while non-numeric strings get ignored.
Testing the new behaviorWe can write tests to ensure that library behaves the way we would expect when strings are passed in…
And if we're using TDD, we would have written these first, then written our code. But what happens when we get to the refactor phase? Changing how the code works under-the-hoodLet's say we look at this bit of code repeated in each of methods…
And decide we want to abstract it into some sort of internal function.
In our methods, we use the
Test behaviors, not implementation detailsHow would you modify your tests to account for this? You wouldn't! The external behavior of our library hasn't changed. How you handle numeric strings is an implementation detail. As long as the behavior is the same, the way you get there doesn't really matter (from a test perspective). Sometimes folks will fixate on how to test the Don't do that! The For this reason, code coverage, the percentage of your library covered by a test, it also a bit of a meaningless metric. Many testing libraries will include functions used in other functions as part of their coverage assessment now. Some will not. Either way, it doesn't particularly matter. If your tests cover 100 percent of the external behaviors of your library and fail for meaningful reasons, you're good. You can download the source code for today's article on GitHub. Cheers, Want to share this with others or read it later? View it in a browser. |
0 Komentar untuk "[Go Make Things] Don't test implementation details"