我正在尝试为我的代码编写测试(我想在下面测试的简单版本),并使用sinon和chai来测试其他东西,但不知道如何编写我的测试来模拟服务调用这样我就可以避免调用外部服务,但可以设置模拟结果,以便我可以处理数据。我会使用重新连线(如果是这样,那将如何运作)?任何帮助将不胜感激!
qf = require('./service/queryFile');
function countByDate(req, res, next){
//do stuff to create variable to pass to service call
var queryCriterion = {
d1 = req.query.d1,
d2 = req.query.d2
}
//make service call and process results
qf.getByDateAsync(queryCriterion)
.then(function(results){
var data = {};
//do some things with results data
data = results.data;
//return data object
res.json({
success: true,
data: data,
});
});
}
module.exports = {
countByDate: countByDate
};
****其他详情****
queryFile:
function getByDate(criterion){
//query from database
//process results
return {
key1: aValue,
key2: bValue,
data: arrayOfObjects
};
}
exports = module.exports = {
getByDate: getByDate,
getByDateAsync: Promise.promisify(getByDate)
};
测试:
var pf = require('./service/processFile');
var qf = require('./service/queryFile');
var req, res;
before(function(){
this.timeout(30000);
});
beforeEach(function(){
res.json = sinon.spy();
res.status = sinon.stub().returns({json: sinon.spy()});
});
describe('test', function(){
it('should return results from countByDate', function(done){
var eDate = new Date();
var sDate = eDate.getDate()-60;
req = res = {};
req.query = {
d1: sDate,
d2: eDate
};
var testData = [{
key1: '',
key2: '',
data: [{aKey: new Date(), count: 100}]
}];
sinon.stub(qf, 'getByDateAsync').returns(Promise.resolve({data:tData}));
pf.countByDate(req,res);
console.log(res.json.data);
}
答案 0 :(得分:0)
我在测试中需要queryFile,然后通过返回带有模拟响应的promise来存根getByDateAsync。
const qf = require('./service/queryFile');
sinon.stub(qf, 'getByDateAsync').returns(Promise.resolve({ data: {}}));