2017-05-25 77 views
0

我想測試我的功能,並堅持使用嘲諷事件。我不知道如何與sinon模擬事件。 這是我的代碼時,我堅持:測試事件sinon node.js

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打電話,我不我不知道該如何嘲笑這件事,並且決心去做。

回答

0

我解決了使用yield的問題。更改pipeMock存根:前

let pipeMock = sinon.stub(); 

在()pipeMock回報率:

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

現在測試呼叫calback和解決承諾