Saturday, 14 November 2015

Require is like new; An argument for DI in Node.js

As I continue my journey in Node.js I have been looking into unit testing. I typically practice TDD but while I was getting started with Node and everything was simple I was happy to play with manual testing and restarts.

I picked Mocha as a test framework. One thing I noticed quickly looking at Mocha was that the examples were simple, adding a few numbers together or checking the type of a return value.
 
Having come to Node from C# I had require littered through my code like they were using statements,  When I tried to implement some tests against the basic logic I had put together I quickly ran into a problem, that was not covered by the simple Mocha examples.  The problem arose because require is not a using statement, it directly provides code from other modules meaning that the code referenced is invoked in the tests.

I went looking for ways to mock out the require statement. As I was looking it occurred to me that mocking require is possibly not the best way to do it. In C# terms require has more in common with a static factory than a using statement.  I feel that require is not something to mock out, rather it's something to isolate.

By bringing the require statements for external modules out of the main code body the code can be broken up into a modular architecture making the system more testable and more resilient to regression issues.

Require is the best reason I have seen on my Node.js journey to include Dependency Injection in a project, even if it is a hand rolled.