如何在mocha中测试具有不同语言环境的moment.js

时间:2016-09-07 09:33:02

标签: javascript mocha locale momentjs

我想用mocha测试依赖于语言环境的日期计算。但是,区域设置似乎不会在不同的describe函数中重置:

var expect = require('chai').expect,
    moment = require('moment');

describe('English locale', function () {
    moment.locale('en');
    it('uses Sunday as start of week', function () {
        // Monday, 5th September 2016
        var d = moment('2016-09-05').weekday(0);
        expect(d.date()).to.equal(4);
    });
});

describe('German locale', function () {
    moment.locale('de');
    it('uses Monday as start of week', function () {
        // Monday, 5th September 2016
        var d = moment('2016-09-05').weekday(0);
        expect(d.date()).to.equal(5);
    });
});

如何在describe块中创建特定的“区域设置”环境?

documentation仅显示如何以特定于语言环境的方式格式化对象,我想在特定区域设置中创建时刻对象。

1 个答案:

答案 0 :(得分:3)

可能的解决方法是本地化各个日期。这可以通过两种方式完成:

1)以不同方式创建它们(仅在从字符串创建时有效)

describe('German locale', function () {
    it('uses Monday as start of week', function () {
        // Monday, 5th September 2016
        var d = moment('2016-09-05', 'YYYY-MM-DD', 'de').weekday(0);
        expect(d.date()).to.equal(5);
    });
});

2)通过显式本地化生成的日期:

describe('German locale', function () {
    it('uses Monday as start of week', function () {
        // Monday, 5th September 2016
        var d = moment('2016-09-05').locale('de').weekday(0);
        expect(d.date()).to.equal(5);
    });
});

您甚至可以使用该函数定义辅助函数并将moment的所有日期构建调用替换为:

function germanMoment() {
    return moment.apply(moment, arguments).locale('de');
}

describe('German locale', function () {
    it('uses Monday as start of week', function () {
        // Monday, 5th September 2016
        var d = germanMoment('2016-09-05').weekday(0);
        expect(d.date()).to.equal(5);
    });
});