how to stub a callback's callback function.

297 views
Skip to first unread message

Zhang Wenlai

unread,
Apr 21, 2015, 7:30:05 PM4/21/15
to sin...@googlegroups.com
passport.use(new BearerStrategy({ passReqToCallback: true },
function(req, accessToken, done) {
accessTokens.validate(req, accessToken, function(err, token) {
if (err) {
req.log.error(err);
return done(null, false);
}
if (!token) { return done(null, false); }

users.getById(req, token.userId, function(err, user) {
if (err) {
req.log.error(err);
return done(null, false);
}
if (!user) { return done(null, false); }

// default to * for now
var info = { scope: '*' };
req.authenticationStrategy = 'OAUTH2';
req.authToken = accessToken;
done(null, user, info);
});
});



When I stub users.getById function, it excutes original function rather than stub function.

Below is my test:

it('test-error: users getbyId error null for bearer strategy', function(done) { //need to
var passport = index.__get__("passport");
var strategy = _.find(passport._strategies, function (value) {
return value.name === 'bearer'
})._verify;
var stub=sinon.stub(users,'getById');
stub.callsArgWith(2,null,null);
var accessToken = theToken;
strategy(context,accessToken,function(err,user){
assert.isNull(err,"err should be null");
assert.isFalse(user,"user should be False");
done();
});
users.getById.restore();

});

Zhang Wenlai

unread,
Apr 22, 2015, 12:38:55 PM4/22/15
to sin...@googlegroups.com
I've got the solution: I need to stub the top level callback first.
sinon.stub(accessTokens,"validate").callsArgWith(2,null,true);
sinon.stub(users,"getById").callsArgWith(2,null,null);
Reply all
Reply to author
Forward
0 new messages