Spying on Date constructor with sinon

狂风中的少年 提交于 2019-12-24 04:29:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!