【问题标题】:Sinon js check stub called with exact arguments使用精确参数调用的 Sinon js 检查存根
【发布时间】:2017-06-29 17:09:03
【问题描述】:

使用精确参数调用的 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();
    });
});

【问题讨论】:

    标签: javascript node.js mocha.js sinon chai


    【解决方案1】:

    这行有两个问题:

    sinon.assert.calledWith(ejsStub, path.join('views/', templateName), data, cb_2);
    

    首先,您希望使用参数 'data' 调用 ejsStub,但是当您实际调用 renderFile 时,您会像这样包装它:{data: data}

    第二个是 cb_2 不等于您实际传递给 renderFile 的 function (error, success) { if (error) ... }

    要让它工作,像这样运行它:

    sinon.assert.calledWith(ejsStub, path.join('views/', templateName), {data: data});

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2015-06-30
      • 2015-07-06
      • 1970-01-01
      • 2020-03-29
      • 2015-03-06
      相关资源
      最近更新 更多