簡體   English   中英

如何用NodeJ中的模擬實現功能單元測試sinon?

[英]How to implement functional unit testing sinon with mocks in NodeJs?

如何在follwing函數上實現sinon.mock。

function getDashboard(req,res){res.send(“success”); }

describe("GetDashboard test"){
    it("Response Should be test", function(){
        const getDashboard = sinon.stub().returns('success');
        let req = {}     
        let res = {
        send: function(){};
        const mock = sinon.mock(res);     
        mock.expect(getDashboard.calledOnce).to.be.true;      
        mock.verify();
      }    
    })
}

還有如何在函數中存根數據。這是正確的模擬方式。

這是一個工作示例:

const sinon = require('sinon');

function getDashboard(req, res) { res.send('success'); }

describe("getDashboard", function () {
  it("should respond with 'success'", function () {
    const req = {};
    const res = { send: sinon.stub() };
    getDashboard(req, res);
    sinon.assert.calledWithExactly(res.send, 'success');  // Success!
  })
});

細節

getDashboard調用send定的res對象的send函數,因此您只需要為send屬性創建一個帶有sinon存根的模擬對象,並驗證它是否按預期調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM