I have tests where Im using getByText
function in react-testing-library
.
Im looking for element in DOM that has value "10-10-2020 12:00"
.
But after daylight saving time change, all my tests have failed because due to the change, the display text has changed to "10-10-2020 13:00"
(one hour forwards) and now Im not able to get those elements. I will have to update my tests, but they will obviously fail once again when the time is changed in winter.
It happens because e.g. new Date('2020-01-01T00:00:00.000Z')
returns 01 01 2020 01:00:00
instead of 01 01 2020 00:00:00
because of the timezones.
Is there any workaround or fix to make my tests resistant to daylight saving time change and timezones?
CodePudding user response:
Setting the hardcoded date and time for jest
should help:
jest.useFakeTimers('modern')
beforeEach(() => {
const hardcodedDate = new Date('2022-03-20T12:00:00Z')
jest.setSystemTime(hardcodedDate.getTime())
})
It means in your tests you will always have the same system time, which will help with daylight saving time change (or any time change)
UPD: to see the date in the tests before the daylight saving you should change the hardcoded day before it started (for example in the UK it's 27 March)