茉莉花约会用moment.js嘲笑 [英] Jasmine date mocking with moment.js

查看:121
本文介绍了茉莉花约会用moment.js嘲笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了moment.js作为日期/时间,但似乎它与Jasmine的模拟功能不相符。我在下面放了一个测试套件,显示我的问题:

I'm using moment.js for date/time in my application, but it seems like it doesn't play well with Jasmine's mocking capabilities. I've put together a test suite below that shows my issue:

jasmine.clock()。mockDate doesn似乎工作了一会儿,而它适用于日期

jasmine.clock().mockDate doesn't seem to work for moment, while it works fine for Date.

describe('Jasmine tests', function () {
    beforeEach(function() {
        jasmine.clock().install();
    });

    afterEach(function() {
        jasmine.clock().uninstall();
    });

    // Pass
    it('uses the mocked time with Date', function() {
        var today = new Date('2015-10-19');
        jasmine.clock().mockDate(today);
        expect(new Date().valueOf()).toEqual(today.valueOf());
    });


    // Fail
    it('uses the mocked time with moment', function() {
        var today = moment('2015-10-19');
        jasmine.clock().mockDate(today);

        expect(moment().valueOf()).toEqual(today.valueOf());
    });
});

为什么日期按预期工作? code>时刻不是吗?是时刻在引擎盖下使用日期

Why does Date work as expected while moment does not? Isn't moment using Date under the hood?

使用Jasmine模拟时刻的正确方法是什么?

What is the right way to mock moment using Jasmine?

推荐答案

jasmine.clock()。mockDate 期望日期作为输入。 日期时刻不完全兼容。如果你在规范中提供了被模拟的日期,你可以在那里使用 Date

jasmine.clock().mockDate expects Date as input. Date and moment are not fully compatible. If you provide the to-be-mocked date in the spec itself you could simply use Date there instead.

如果您的代码生成了想要模拟的时刻,或者您更愿意使用时刻API,请查看 moment.toDate() 。此方法返回支持片刻的 Date 对象。

If your code generates a moment you want to mock, or you'd rather use the moment API, take a look at moment.toDate(). This method returns the Date object backing a moment.

it('uses the mocked time with moment', function() {
    var today = moment('2015-10-19').toDate();
    jasmine.clock().mockDate(today);
    expect(moment().valueOf()).toEqual(today.valueOf());
});

这篇关于茉莉花约会用moment.js嘲笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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