Tip 32: Write Functions for Testability

In this tip, you'll learn about writing functions for testability and dependency injection.

I had a literature professor who said that classes about writing don’t include enough reading and classes about reading don’t include enough writing. The same is true of code and tests: Books about code don’t talk enough about testing and books about testing don’t talk enough about composing code.

Time to fix that.

Testing

Testing is important. If you don’t do it, you should. It makes your code easier to refactor. It makes legacy code much easier to understand. And it generally results in cleaner, less buggy applications.

Most developers agree with this. Why then is testing neglected?

It’s simple. Writing tests is hard. Or more accurately, many developers think writing tests is hard because they try to fit tests onto their existing code. And their existing code is tightly coupled with external dependencies.

Code that’s hard to test is often unnecessarily complex. Instead of struggling to make tests for your code, you should focus on writing code that is testable. Your code will improve, your tests will be easier to write, and the user experience will be identical. There’s nothing to lose.

If you’re new to testing, check the documentation for one of three popular testing frameworks—jasmine, mocha, or jest—for some quick pointers. You can also check out the testing of the code for this course in the end, which has near 100% code coverage using mocha as the test runner.

To get the most out of this tip, you should know the basics of describe() and it() functions along with expectations.

Writing testable code

Now, how do you write testable code? Here’s a function that looks simple but has some subtle complexity.

Get hands-on with 1200+ tech skills courses.