Reputation: 79
So I have this method I want to test:
app.get('/test', exposeDb, function(req, res) {
req.dbService.getUserByID( function(err, result) {
if (result == 5) {
res.statusCode = 200;
}
else {
res.statusCode = 500;
}
});
});
And I'm trying to stub it so the getUserByID method returns a value so I do this:
describe('Test', function() {
beforeEach(function() {
var getUserByIDStubE = sinon.stub(dbService, 'getUserByID').callsFake(() => {
return 5;
});
});
it('TESTSETSTETS', function(done) {
chai.request(server)
.get('/test')
.send({})
.end(function (err, res) {
res.should.have.status(200);
});
done();
});
});
The problem is, the code inside the req.dbService.getUserByID is never called so I can't check the logic of whether the "result" is equal to 5 or not.
If I console.log(req.dbService.getUserByID()), that indeed returns the stubbed value of 5. But I do not know how it works on callback.
How do I make it so it returns 5 in my example (to then check the res.statusCode)?
Thanks in advance!
Upvotes: 0
Views: 318
Reputation: 92440
You don’t need callsFake()
to get getUserByID
tocall the callback so that you can test that res.statusCode
is set properly. The sinon function you want here is stub.yields()
which is made specifically for this purpose and will call the first callback passed to the function with arguments you provide.
var getUserByIDStubE = sinon.stub(dbService, 'getUserByID').yields([null, 5]);
This will cause the callback you are passing to getUserByID
to be called with no error and a value of 5 or whatever value you want to test.
Upvotes: 2
Reputation: 46323
Looks like you're function is getting a callback and calling that with the result, and not returning the result as your stub.
Try like this:
sinon.stub(dbService, 'getUserByID').callsFake(cb => {
cb(undefined, 5);
});
Upvotes: 2