这是在Node中做dependency injection的正确方法吗?

我最近启动了一个节点项目,作为一名testing驱动开发人员,我用我的全新模块很快遇到了dependency injection问题。 以下是我如何计算出我应该做dependency injection。 注意我使用誓言作为BDD框架并且用Sinon扩展它是重要的。

我的模块:

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

我的testing:

 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); 

你认为这是正确的路? 我喜欢这个解决scheme,因为当你使用这个模块的时候不需要更多的东西(比如在require语句之后加上“(”))。

用testing的东西来垃圾你的代码是不好的方法。 你的代码的第2行

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

看起来不需要的界面。 我build议你把它replace

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

更干净。 在testing中,只是模拟'ezcrypto'模块的Crypto方法。 使用后不要忘记恢复。