I want testing my function and I stuck with mocking events. I don't know how mock event with sinon. This is my code when I stuck:
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);
})
})
Problem occured when I want test
result.on('finish',resolve);
This is my test:
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);
});
Test not pass to onMock call and I don't have idea how mock this event and resolves to next then.
via MichaĆ Niedziela
No comments:
Post a Comment