Testing – pure versus impure
We have seen how pure functions are conceptually better than impure ones, but we cannot set out on a crusade to vanquish all impurities from our code. First, no one can deny that side effects can be useful, or at least unavoidable: you will need to interact with the DOM or call a web service, and there are no ways to do this in a pure way. So, rather than bemoaning the fact that you have to allow for impurity, try to structure your code to isolate the impure functions and let the rest of your code be the best it can possibly be.
With this in mind, you’ll have to be able to write unit tests for all kinds of functions, pure or impure. Writing unit tests is different, in terms of difficulty and complexity, for pure and impure functions. While coding tests for the former is usually quite simple and follows a basic pattern, the latter usually requires scaffolding and complex setups. So, let’s finish this chapter by seeing how to go about...