用 sinon 监视 Date 构造函数

Spying on Date constructor with sinon

我有一个设置令牌到期日期的方法:

var jwt = require('jwt-simple');
module.exports = {  
    setExpirationDate: function(numDays) {
        var dateObj = new Date();
        console.log(dateObj);
    }
}

我想在 "new Date" 语句上写断言:

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;
    });
});

测试失败:

AssertionError: expected spy to have been called at least once, but it was never called

构造函数间谍有什么需要注意的地方吗?

考虑到您的构造函数绑定到 'global',这意味着如果您在浏览器上打开开发人员控制台,您应该能够通过使用相关的 function/constructor 来实例化一个对象:

var Date = new Date();

如果是这样,实际工作代码可能是:

var Date = sinon.spy(global, 'Date');

expect(Date.called).to.be.equal(true);