[英]testing events sinon node.js
我想測試我的功能,並且堅持使用模擬事件。 我不知道如何與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調用,我不知道如何模擬此事件,然后解決下一個問題。
我解決了使用收益的問題。 將pipeMock更改為存根:
let pipeMock = sinon.stub();
在before()pipeMock返回收益:
pipeMock.returns({ on: sinon.stub().yields()});
現在測試電話回撥並解決承諾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.