Dependency injection in JavaScript: Write testable code easily

Click for: original source

I struggled with two aspects of software development as a junior engineer: structuring large codebases and writing testable code. Test-driven development is such a common technique that is often taken for granted, but it’s not always clear how code can be made fully testable. By Nate Anderson.

This article shares a few powerful tools to help you write testable code that grows into neat, manageable code bases:

  • What is a dependency?
  • SOLID principles
  • Single responsibility principle
  • Dependency inversion principle
  • Example: An overwhelmed express handler for Node.js
  • Layered architecture for separation of concerns in JavaScript
  • Separation of concerns: An example
  • Mocking on the Fly with Jest
  • Benefits of mocking

The dependency inversion principle encourages us to depend on abstractions instead of concretions. This, too, has to do with separation of concerns. Observing the single responsibility principle means that we only unit test the one purpose a unit of code fulfills. In this post, we’ve taken a concrete example of an overwhelmed function and replaced it with a composition of smaller, testable units of code. Even if we accomplish identical lines-of-code test coverage for both versions, we can know exactly what broke and why when tests fail in the new version. Nice one!

[Read More]

Tags nodejs javascript web-development frontend tdd