0

I am currently new to Sinon, Mocha, Supertest and in the process to writes tests. In my current scenario, i have authentication library which verifies my "OTP" and after verifying it proceeds to do operation within the callback function.

I am unable to mock the callback to return null and carry on to test rest of the code. Following is my code snippet:

Controller.js


var authy = require('authy')(sails.config.authy.token);
 authy.verify(req.param('aid'), req.param('oid'), function(err, response) {
  console.log(err);
  if (err) {
    return res.badRequest('verification failed.');
  }
....

My test is :

 var authy = require('authy')('token');



describe('Controller', function() {
  before(function() {
    var authyStub = sinon.stub(authy, 'verify');
    authyStub.callsArgWith(2, null, true);
  });

  it('creates a test user', function(done) {
    // This function will create a user again and again.
    this.timeout(15000);
    api.post('my_endpoint')
      .send({
        aid: 1,
        oid: 1
      })
      .expect(201, done);


  });
});

I essentially want to call authy verify get a null as "err" in callback, so i can test the rest of the code.

Any help would be highly appreciated. Thanks

Aditya Patel
  • 569
  • 1
  • 10
  • 28

1 Answers1

0

The trouble is that you're using different instances of the authy object in your tests and your code. See here authy github repo.

In your code you do

var authy = require('authy')(sails.config.authy.token);

and in your test

var authy = require('authy')('token');

So your stub is generally fine, but it will never work like this because your code does not use your stub.

A way out is to allow for the authy instance in your controller to be injected from the outside. Something like this:

function Controller(authy) {
    // instantiate authy if no argument passed

in your tests you can then do

describe('Controller', function() {
    before(function() {
        var authyStub = sinon.stub(authy, 'verify');
        authyStub.callsArgWith(2, null, true);
        // get a controller instance, however you do it
        // but pass in your stub explicitly
        ctrl = Controller(authyStub);
    });
});
nomve
  • 736
  • 4
  • 14
  • Thanks @nomve for the reply ! I have been breaking my head on this for awhile. How do you pass an argument to a "Controller". Since currently i am calling a "create" function eg. module.exports{ create: function(req, res, next) { ..... – Aditya Patel Nov 11 '16 at 10:53
  • I don't know how your controller.js file looks like. However it looks like, and whatever the piece of code using authy looks like, you'd need to pass in your stubbed instance in it. Otherwise you can't really stub it. – nomve Nov 11 '16 at 18:04