Using Sinon to stub Mongoose calls and return Promise

Suppose we have a schema

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;

Finally, assertion will as follows

it('Should get target user', function (done) {
  getUserById().then(function (user) {


This is the sample example to start writing unit test……….

You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

Leave a Reply

Your email address will not be published. Required fields are marked *