根据上面@AlbertZaccagni 的建议,我查阅了 sinon 的文档,得出以下结论:
注意:我省略了一些代码,这些代码声明了手头问题的路线和其他非必要部分。
假设 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.*/
});
}
在我的测试文件夹中,我创建了一个名为 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();
});
});
});
当我在我的工作目录上运行 npm test 时,我看到它没有实际调用数据库就通过了,它为用户名 1 返回 100。