问题
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
回答1:
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);
});
});
来源:https://stackoverflow.com/questions/40541969/sinon-how-to-stub-authentication-library-authy-twilio