简体   繁体   中英

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

How to implement sinon.mock on follwing function.

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

Also how to stubbing data in function.Is it correct way of mocking.

Here is a working example:

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!
  })
});

Details

getDashboard calls the send function of the res object that it is given, so you just need to create a mock object with a sinon stub for the send property and verify that it was called as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM