8

Is it possible to mock a timezone in Jasmine to test a date object?

I have a function which takes A UTC time string and converts it to a date object.

Using "2016-01-16T07:29:59+0000", I want to be able to verify that when we are in PST we are observing 2016-01-15 23:29:59 as the local date/time

I'd like to be able to switch this time zone back to GMT and then ensure that we observe 2016-01-16 07:29:59 as the local date/time

(How) is this possible? (I am running my Jasmine spec through Grunt with phantomjs)

My function for reference:

utcDateStringToDateObject: function(dateString){
    return dateString.indexOf('+')>-1 ? new Date(dateString.split('+')[0]) : new Date(dateString);
}
Fraser
  • 14,036
  • 22
  • 73
  • 118
  • Are you working with angular? If so you can create a factory called Date, which you then mock in Jasmine as you would mock anything. If not then same logic of using a factory applies. – andyhasit Jan 25 '16 at 04:15
  • @andyHaslt Unfortunately not. This is a backbone project. Cheers – Fraser Jan 25 '16 at 09:21
  • 1
    Well you can always overwrite the Date function in an individual test. Otherwise how about https://github.com/sinonjs/lolex – andyhasit Jan 25 '16 at 13:38
  • 1
    Some additional info here: http://stackoverflow.com/questions/15141762/how-to-initialize-javascript-date-to-a-particular-timezone – andyhasit Jan 25 '16 at 14:03
  • What functionality are you trying to test here? What is the spec for your test? Are you testing weather the browser is doing conversions correctly? – sabithpocker Mar 26 '18 at 09:17

1 Answers1

1

I am using jasmine 3.4.0, one solution is to use the clock

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

However, since my tests included timezones, I had to spyOn my service

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');
    });
Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81