【问题标题】:Mock external dependency模拟外部依赖
【发布时间】:2012-01-19 15:34:17
【问题描述】:
//user.js

couchdb = require('couchdb');

exports.create = function(req, res){

  user = req.body

  if( validate(user) ) {

    couchdb('db').insert(user);
    //redirect

  } else {

    //render new again with the user

  };

};

我想测试上述函数是否创建了用户。

//user_spec.js

describe('User create', function(){

  beforeEach( function(){
    //call create with valid user
  });

  it('should create a user', function(){

    //test database for user
    assert( fakeDatabase.users.length, 1)

  });

})

有没有人知道用假对象替换 couchdb 对象的方法,这样我就可以测试是否创建了用户。我真的不想在我的单元测试中调用真正的 couchdb。

【问题讨论】:

    标签: javascript node.js express mocha.js


    【解决方案1】:

    找到了几个解决方案。第一个是显式向模块添加依赖项。

    module.exports = function(dependency){
       var dependency = dependency | require('dependency');
    };
    

    在此处找到此解决方案:http://csausdev.wordpress.com/2010/12/17/dependency-injection-in-node-js/

    我发现的第二个方法是使用自定义文件加载器加载文件并以这种方式替换模块。这里解释一下:http://howtonode.org/testing-private-state-and-mocking-deps

    【讨论】:

      【解决方案2】:

      试试nock。您可以模拟 http(s) 请求,但您必须跟踪自己添加的用户。

      var scope = nock('http://myapp.iriscouch.com')
                      .get('/')
                      .reply(200, {username: 'pgte', email: 'pedro.teixeira@gmail.com', _id: "4324243fsd"});
      

      【讨论】:

      • 认为问题的标题引起了一些混乱。我想模拟模块内的依赖项。不过诺克看起来不错。
      猜你喜欢
      • 2019-01-18
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多