3

I have a function that translates a date in format 2021-06-07T07:28:55.69725+00:00 into string of hours and minutes in format 07:28

export function getTime(dateTime: string) {
  return dayjs(dateTime).format("HH:mm");
}

Currently I'm locating in UTC+5, so the answer of this function to the argument 2021-06-07T07:28:55.69725+00:00 is 12:28. I want to test the work of the function but I need to mock timezone so that tests would be ok on machines in different timezones. I tried next code but it still returns 12:28.

import dayjs from "dayjs";
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(timezone)

describe('Function getTime', () => {
  beforeEach(() => {
    dayjs.tz.setDefault('Europe/Moscow');
  })

  afterEach(() => {
    dayjs.tz.setDefault();
  })

  it('should return time in format hh:mm', () => {
    const dateTime = '2021-06-07T07:28:55.69725+00:00';
    expect(getTime(dateTime)).toEqual('10:28');
  })
})
Lin Du
  • 88,126
  • 95
  • 281
  • 483
Дарья
  • 147
  • 1
  • 12

1 Answers1

0

The problem is, that dayjs.tz.setDefault('Europe/Moscow') affects only dayjs.tz(). It means, that dayjs() will still show your local time.

You should change your function:

export function getTime(dateTime: string) {   
    return dayjs.tz(dateTime).format("HH:mm"); 
}

Now it should work as you expect.

Tigran Petrosyan
  • 524
  • 4
  • 14