testingHapijs端点而不碰到数据库

我正在使用Hapi js开发restApi。 该项目的结构如下:

|-Root server.js |-router routes.js |-handlers authHandler.js |-db userDb.js 

一个authentication请求将命中routes.js并转发给authHandler.js,然后调用userDb.js。 userDb.js与数据库进行通信并将结果返回给authHandler.js,该响应将响应返回给客户端。

我一直在试图写一个testing,其中userDb.js不会与数据库交谈

为此,我使用Hapi的inject来调用路由,而不需要真正启动服务器。 我正在努力弄清楚如何模拟调用链中的数据库,以便我可以提供一个虚拟的响应。

所以简而言之,我想在testing时将userDb.jsreplace为模拟。

在上面@AlbertZaccagni的build议之后,我咨询了sinon的文档 ,并且提出了以下内容:

注意:我已经省略了一些代码来说明path和其他非关键部分。

假设userDb.js是连接到数据库的模块,并且我想模拟来自数据库的响应:

userDb.js看起来像这样:

 var db = require(/*path to db */); module.exports.getUser = function(id, callback){ db.query('sql query', function(err, rows){ if(err){ return callback(err); } return callback(null, rows[0]);/*returns the first object- in the resultset from the database.*/ }); } 

在我的testing文件夹里面,我创build了一个名为mytest.js的文件,内容如下:

 //don't forget to install sinon JS via npm var sinon = require('sinon'); var server = require(/*path to hapi server*/); var userDb = require(/*path to the module we are stubbing/mocking*/); describe('Stub test', function(){ var options = {}; options.method = 'GET'; options.url = '/user/1'; it('with stubbing', function(done) { var stub = sinon.stub(userDb, 'getUser', function(id, callback) { if (id < 5) { return callback(null, 100);/*in this case i'm just testing to see if this function will get called instead- of the actual function. That's why 100.*/ } return new Error('test error'); }); server.inject(options, function(res) { var result = res.result; res.statusCode.should.equal(200); result.num.should.equal(100); done(); }); }); }); 

当我在我的工作目录上运行npmtesting时,我发现它在没有真正调用数据库的情况下通过,它返回100为用户名1。