如何在NodeJ中使用模拟实现功能单元测试sinon?

时间:2019-04-01 10:06:27

标签: node.js sinon

如何在以下功能上实现sinon.mock。

  

函数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();
      }    
    })
}

还如何在函数中存根数据。这是正确的模拟方式。

1 个答案:

答案 0 :(得分:0)

这是一个有效的示例:

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函数,因此您只需要为{{ 1}}属性,并验证它是否按预期方式调用。

相关问题