Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 模拟外部依赖_Javascript_Node.js_Express_Mocha.js - Fatal编程技术网

Javascript 模拟外部依赖

Javascript 模拟外部依赖,javascript,node.js,express,mocha.js,Javascript,Node.js,Express,Mocha.js,我想测试上面的函数是否创建了一个用户 //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.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

  };

};

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

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

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

  });

})
在此处找到此解决方案:

我发现的第二个方法是使用自定义文件加载程序加载文件,并以这种方式替换模块。这里有解释:

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

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

我想问题的标题引起了一些混乱。我想模拟模块内的依赖项。诺克看起来不错。
var scope = nock('http://myapp.iriscouch.com')
                .get('/')
                .reply(200, {username: 'pgte', email: 'pedro.teixeira@gmail.com', _id: "4324243fsd"});