PhantomJS中用于茉莉花测试的模拟时区

时间:2016-01-22 11:00:43

标签: javascript unit-testing date jasmine phantomjs

是否可以在Jasmine中模拟时区来测试日期对象?

我有一个函数,它接受一个UTC时间字符串并将其转换为日期对象。

使用" 2016-01-16T07:29:59 + 0000",我希望能够验证当我们在PST时我们正在观察2016-01- 15 23:29 :59 作为当地日期/时间

我希望能够将此时区切换回GMT,然后确保我们将2016-01- 16 07:29:59 视为本地日期/时间< / p>

(怎么样)这可能吗? (我通过Grunt用phantomjs运行我的Jasmine规范)

我的参考功能:

utcDateStringToDateObject: function(dateString){
    return dateString.indexOf('+')>-1 ? new Date(dateString.split('+')[0]) : new Date(dateString);
}

1 个答案:

答案 0 :(得分:0)

我正在使用茉莉花3.4.0,一种解决方案是使用时钟

    beforeEach(() => {
        jasmine.clock().install();
        // whenever new Date() occurs return the date below
        jasmine.clock().mockDate(new Date('2024-04-08T06:40:00'));
    });

    afterEach(() => {
        jasmine.clock().uninstall();
    });

但是,由于我的测试包括时区,所以我不得不监视我的服务

it('should support work', () => {
        const mocked = moment.tz('2019-03-27 10:00:00', 'America/New_York');
        spyOn(spectator.service, 'getMoment').and.returnValue(mocked);
        const output = spectator.service.foo('bar');
        // My asserts
        expect(output.start.format(dateFormat)).toBe('2019-03-17T00:00:00-04:00');
        expect(output.end.format(dateFormat)).toBe('2019-03-23T23:59:59-04:00');
    });