Last active
May 23, 2023 08:25
-
-
Save delwar2016/c06132ca12e1304f99afa397c01de7cc to your computer and use it in GitHub Desktop.
Using Sinon to stub Mongoose calls and return Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Suppose we have a schema as follows | |
var User = require('./schemas/UserSchema').User; | |
and we want to write unit test for like bellow code: | |
var getUserById = function () { | |
return User.findOne({_id: '001'}).exec(); | |
}; | |
Before writing unit test we can mock the data in the following way: | |
var user = { | |
_id: '001', | |
username: 'user-001' | |
}; | |
var mockFindOne = { | |
exec: function () { | |
return Promise.resolve(user); | |
} | |
}; | |
var userFindOneStub = sinon.stub(User, "findOne", function(conditions) { | |
if (conditions['_id'] === '001') { | |
return mockFindOne; | |
} | |
}); | |
This is the sample example to start writing unit test.......... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sinon stub has been removed