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

问题描述 投票:0回答:1

如何在以下函数上实现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();
      }    
    })
}

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

node.js sinon
1个回答
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函数,因此你只需要为sinon属性创建一个带有send存根的模拟对象,并验证它是否按预期调用。

© www.soinside.com 2019 - 2024. All rights reserved.