【问题标题】:testing events sinon node.js测试事件 sinon node.js
【发布时间】:2017-05-25 13:01:36
【问题描述】:

我想测试我的功能,但我坚持使用模拟事件。我不知道如何用 sinon 模拟事件。 这是我卡住时的代码:

return pdfGenerator(invoice)
                            .then(content =>
                            {
                                const printer = new PdfMakePrinter(fonts);
                                let pdfDoc = {};
                                try {
                                    pdfDoc = printer.createPdfKitDocument(content);
                                } catch (error) {
                                    throw applicationException.new(applicationException.ERROR, 'Something bad in pdf content: ' + error);
                                }

                                let filepath = path.join(__dirname, '../REST/uploads/', filename);
                                let result = pdfDoc.pipe(fs.createWriteStream(filepath));
                                pdfDoc.end();
                                return new Promise(resolve =>
                                {
                                    result.on('finish', resolve);
                                })
                            })

我要测试时出现问题

result.on('finish',resolve);

这是我的测试:

let pdfGeneratorMock = sinon.stub();
let endMock = sinon.stub().callsFake(function ()
{
    return 0;
});
let pipeMock = sinon.spy();
let createPdfKitDocumentMock = sinon.spy(() =>
{
    return {
        end: endMock,
        pipe: pipeMock
    }
});
let pdfMakePrinterMock = sinon.spy(function ()
{
    return {
        createPdfKitDocument: createPdfKitDocumentMock
    }
});
let onMock = sinon.spy(function(text,callback){
    return callback();
});
let writeStreamMock = sinon.spy(() =>
{
    return {
        on: onMock
    }
});
let fs = {
    mkdirSync: sinon.spy(),
    createWriteStream: writeStreamMock
};
........

it('should call createPefKitDocument', function ()
  {
       expect(createPdfKitDocumentMock).callCount(1);
  });
it('should call fs.createWriteStream', function ()
{
    expect(writeStreamMock).callCount(1);
});

it('should call pipe', function ()
{
    expect(pipeMock).callCount(1);
});
it('should call end', function ()
{
    expect(endMock).callCount(1);
});

it('should call on', function ()
{

    expect(onMock).callCount(1);
});

测试没有传递给 onMock 调用,我不知道如何模拟这个事件并解析到下一个。

【问题讨论】:

    标签: node.js events sinon


    【解决方案1】:

    我解决了使用产量的问题。将 pipeMock 更改为存根:

    let pipeMock = sinon.stub();
    

    在 before() pipeMock 中返回收益率:

    pipeMock.returns({ on: sinon.stub().yields()});
    

    现在测试调用回调并解决承诺

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 2017-12-14
      • 2016-07-01
      • 2017-03-25
      相关资源
      最近更新 更多