用 moment.js 模拟茉莉花日期

Jasmine date mocking with moment.js(用 moment.js 模拟茉莉花日期)
本文介绍了用 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 似乎暂时不起作用,而对于 Date 却可以正常工作.

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

为什么 Date 能按预期工作,而 moment 不能?moment 不是在底层使用 Date 吗?

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

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

What is the right way to mock moment using Jasmine?

推荐答案

jasmine.clock().mockDate 期望 Date 作为输入.Datemoment 不完全兼容.如果您在规范本身中提供要模拟的日期,您可以简单地使用 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 模拟茉莉花日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)