Adapters and Inject-Loader
Using inject-loader with adapters to make testing easier in node.js
Testing is important. However, testing a fully working system is a bit of a trial- especially if it has side effects. A pretty common side effect is to call on a third party interface; and I don’t know of that many API’s which are overly tolerant of a ‘oh- but I was just testing’ attitude.
There’s a myriad of patterns out there to cope with this aspect of programming, and the one I’m fairly fond of is the ‘adapter’ pattern. That is, you write a module which explicitly defines the interface with the third party- for example, it might have the function getUserById(id)
as a wrapper around the database.
As well as making your intention and contract with these interfaces tight and explicit, it also provides a helpful way to mock- as you can ‘simply’ replace a live production adapter with a testing one; one which will behave as demanded by the tests themselves.
The best way I’ve found of achieving this with the webpack/node stack is to use the fantastic inject-loader. This allows you to write your modules against adapters, and then swap them out in your test suite, as follows:
Thanks to mocha-webpack this example is written in ES6. It uses chai and sinon to allow me to specify what success looks like (i.e. my postman can be given a letter with a vague address and deliver it to the right place.) These are all great libraries, and I would recommend you take a look at them.
The interesting bit, however, is the injection. On line 11 I use the webpack loader syntax to load the original ../src/post
module with the inject-loader. Instead of returning the actual module, the inject-loader returns a function with the pseudo-signature: ({ modulePathInFiletoReplace: objectToUseInstead }) => ({ moduleLoadedWithReplacements })
.
This allows us to take out our actual mailer
module, which would send an e-mail (not ideal in a test environment), and replace it with our testMailer
. Armed with the ability to switch out adapters, we can then be clever and put spies in our test adapter- allowing us to verify that post
has done its job properly.
So- go forth and inject!