使用sinon监视Date构造函数 [英] Spying on Date constructor with sinon

查看:83
本文介绍了使用sinon监视Date构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

测试失败,并显示:

AssertionError:预期间谍至少被调用过一次,但是它 从来没有被叫过

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?

推荐答案

考虑到您的构造函数已绑定到全局",这意味着,如果您在浏览器上打开开发者控制台,则应该能够通过使用相关对象来实例化对象功能/构造函数:

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

这篇关于使用sinon监视Date构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆