使用精确参数调用的Sinon js检查存根
要求:我想测试用正确参数调用的ejs.renderFile。
我的功能文件: html_to_pdf_converter.js
var ejsToPdfConvert = function (template, data, callback) {
var row = data.voucher;
html = ejs.renderFile(
path.join(__dirname+'/../../views/', template),
{
data: data
},
function (error, success) {
if (error) {
callback(error, null);
} else {
var pdfPath = getPdfUploadPath(row);
htmlToPdf.convertHTMLString(success, pdfPath, function (error, success) {
if (error) {
if (typeof callback === 'function') {
callback(error, null);
}
} else {
if (typeof callback === 'function') {
callback(null, success, pdfPath);
}
}
});
}
});
};
Mt测试是:html_to_pdf_converter.test.js
describe("ejs to html converter", function () {
it('ejs to html generation error', function() {
var data = {
voucher: {},
image_path: 'tmp/1.jpg',
date_format: '',
parameters: ''
};
var cb_1 = sinon.spy();
var cb_2 = sinon.spy();
var ejsStub = sinon.stub(ejs, 'renderFile');
var pathStub = sinon.stub(path, 'join');
ejsStub.callsArgWith(2, 'path not found', null);
htmlToPdfConverter.ejsToPdfConvert('voucher', data, cb_1);
sinon.assert.calledOnce(ejs.renderFile);
sinon.assert.calledOnce(path.join);
sinon.assert.calledOnce(cb_1);
sinon.assert.calledWith(ejsStub, path.join('views/', templateName), data, cb_2); //Error in this line
ejsStub.restore();
pathStub.restore();
});
});
答案 0 :(得分:1)
以下是此行的两个问题:
sinon.assert.calledWith(ejsStub, path.join('views/', templateName), data, cb_2);
首先,您希望使用参数' data'来调用ejsStub。但是当你实际调用renderFile时,你可以像这样包装它:{data: data}
。
第二个是你实际传递给renderFile的cb_2不等于function (error, success) { if (error) ... }
。
为了使其正常运行,请执行以下操作:
sinon.assert.calledWith(ejsStub, path.join('views/', templateName), {data: data});

无需传递cb_2或其他任何内容,因为实际的回调是在函数中定义的,无法更改。