Is this the right way to do dependency injection in Node?

I recently started a node project and as a test developer, I quickly ran into the problem of dependency injection with my new module. Here, as I understand it, I have to do an injection of addiction. It is important to note that I use vows as a BDD structure and extend it with Sinon .

My module:

exports.myMethod = function () { var crypto = exports.cryptoLib || require('ezcrypto').Crypto; crypto.HMAC( crypto.SHA256, 'I want to encrypt this', 'with this very tasty salt' ); }; 

My test:

 var vows = require('vows'), sinon = require('sinon'); vows.describe('myObject').addBatch({ 'myMethod':{ 'topic':true, 'calls ezcrypto.HMAC':function () { var myObject = require('../playground.js'); var mock = sinon.mock(require('ezcrypto').Crypto); myObject.cryptoLib = mock; myObject.cryptoLib.HMAC = mock.expects("HMAC").once().withExactArgs( require('ezcrypto').Crypto.SHA256, 'I want to encrypt this', 'with this very tasty salt' ); myObject.cryptoLib.SHA256 = require('ezcrypto').Crypto.SHA256; myObject.cryptoLib = mock; myObject.myMethod(); mock.verify(); } } }).export(module); 

Do you think this is the right way? I like this solution because it does not require more when you use the module (for example, adding "()" after the require statement).

+4
source share
1 answer

This is not a good way to recycle your code using test materials. Line 2 of your code

 var crypto = exports.cryptoLib || require('ezcrypto').Crypto; 

Looks like an unnecessary interface. I suggest you replace it with

 var crypto = require('ezcrypto').Crypto; 

Significantly cleaner. And in the test, just scoff at the crypto method of the ezcrypto module. Just remember to bring it back after use.

+3
source

Source: https://habr.com/ru/post/1393991/


All Articles