stubbing a Mongoose model

81 views Asked by At

I'm trying to unit test this function:

exports.createToken = function( user ){

  var tokenExpirationDate = moment().add( config.tokenExpiration, 'minutes' ).valueOf(),
      payload = {
        sub: user.id,
        exp: tokenExpirationDate
      },
      token = jwt.sign( payload, config.tokenSecret ),
      userInfo = user.toJSON();

  delete userInfo._id;
  delete userInfo.__v;
  delete userInfo.password;

  return {
    user: userInfo,
    token: token,
    expires: tokenExpirationDate
  };
};

Since the idea is to not have dependencies, I have to stub the mongoose model that the function receives.

Since i have little to no experience in unit testing my first thought was to do something like this in mocha:

describe( '#createToken', function() {
  it( 'should return a jwt token', function( done ) {

    var fakeUserModel = {
       id: '558480eeffa8528c15492361',
       _id: '558480eeffa8528c15492361',
       __v: '0',
       toJSON: function(){
         return {
           email: '[email protected]',
           password: '123456',
           username: 'foo'
         }
       }
     }

    var token = auth.createToken(fakeUserModel);

    token.should.have.property('user').and.be.an( 'object' );
    token.user.should.have.property('email','[email protected]').and.be.a('string');
    token.user.should.have.property('username','foo').and.be.a('string');
    token.should.have.property('token').and.be.a( 'string' );
    token.should.have.property('expires').and.be.a( 'string' );

    done();
  });
});

Is there another way to achieve this, perhaps using sinon/rewire ?

0

There are 0 answers