我正在尝试对此功能进行单元测试:
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
};
};
由于想法是没有依赖关系,我必须存根函数接收的mongoose模型。
由于我对单元测试几乎没有经验,我首先想到的是在mocha中做这样的事情:
describe( '#createToken', function() {
it( 'should return a jwt token', function( done ) {
var fakeUserModel = {
id: '558480eeffa8528c15492361',
_id: '558480eeffa8528c15492361',
__v: '0',
toJSON: function(){
return {
email: 'foo@bar.org',
password: '123456',
username: 'foo'
}
}
}
var token = auth.createToken(fakeUserModel);
token.should.have.property('user').and.be.an( 'object' );
token.user.should.have.property('email','foo@bar.org').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();
});
});
还有另一种方法可以实现这一点,也许是使用sinon / rewire?