randy
randy

Reputation: 1887

using nodejs, mocha, chai and sinon i would like to stub a function that is called in a route

I have a pretty simple app that is nodejs, express and mysql I am new to unit testing and i think this app is a great way to do better. what i am trying to accomplish ( and i think sinon is the answer) is to mock or stub mysql.insertEventIntoDB and rabbit.addToRabbitMQ

in my app i have

app.use('/sendgrid', sendgrid(pool, config, logger) );

in my sendgrid.js i have

var express = require('express');
var mysql = require('../app/utils/mysql');
var rabbit = require('../app/utils/rabbitMQ');

module.exports = function (dbpool, config, logger) {
  var router = express.Router();

  router.post('/callback', function (req, res) {
    for (var x=0 ; x < req.body.length ; x++ ){
       mysql.insertEventIntoDB(dbpool, req.body[x], logger);
       rabbit.addToRabbitMQ(config,req.body[x], logger)
    }
    res.json({ status: 'OK' });
  });

  return router;
}

i have seen lots of example of stubs and spys but just can not figure out how to do it from these test. this is an example of one of my tests

it('should get an OK for delivered POST', function(done) {
 chai.request(server)
  .post('/sendgrid/callback')
  .send(delivered)
  .end(function(err, res){
    res.should.have.status(200);
    res.should.be.json;
    res.body.should.be.a('object');
    res.body.should.have.property('status');
    res.body.status.should.equal('OK');
    done();
  });
 });

thanks for any help/direction

Upvotes: 0

Views: 1398

Answers (1)

zangw
zangw

Reputation: 48526

Please try to use sinon.stub

var stub = sinon.stub(object, "method");

To fake the mysql.insertEventIntoDB

var fakeInsertEvt = sinon.stub(mysql, 'insertEventIntoDB');

Then to define its behavior when this fake function is called, the parameter of onCall is the number of this function is called.

fakeInsertEvt.onCall(0).return(0);

Or according to var stub = sinon.stub(object, "method", func);, to fake the above function with one callback function

var fakeInsertEvt = sinon.stub(mysql, 'insertEventIntoDB', function(){
                                          return Math.random();
                                    });

In your case, it seems the second option could be better since there is for loop out of the mysql.insertEventIntoDB.

Upvotes: 2

Related Questions