问题
I have a method that sets expiration date of a token:
var jwt = require('jwt-simple');
module.exports = {
setExpirationDate: function(numDays) {
var dateObj = new Date();
console.log(dateObj);
}
}
I want to write an assert on "new Date" statement:
var jwtHelper = require('../../../helpers/jwtToken');
describe('setExpirationDate method', function() {
it('should create date object', function() {
var Date = sinon.spy(Date);
jwtHelper.setExpirationDate(global.TOKEN_EXPIRE_DAYS);
expect(Date).to.be.called;
});
});
The test fails with:
AssertionError: expected spy to have been called at least once, but it was never called
Are there some things regarding constructor spies that should be concerned?
回答1:
Considering your constructor is bound to 'global' which means that if you open developer console on your browser, you should be able to intantiate an object by using the related function/constructor as such:
var Date = new Date();
If so actual working code could be:
var Date = sinon.spy(global, 'Date');
expect(Date.called).to.be.equal(true);
来源:https://stackoverflow.com/questions/32338427/spying-on-date-constructor-with-sinon