Reputation: 281
I have a jest test failing on the date and time, which I think is because the computer settings are different for the user running it. It is a snapshot test, and it's not an accurate failure because we want to show whatever time zone the user has.
- 11:59:42 AM 7/26/2019
+ 11:59:42 26/07/2019
In my code there’s a getTimeValue which is used to format date to time with point.timestamp.toDate().toLocaleTimeString().
I tried this approach and this one too but it didn't change the output at all:
let mockDate;
beforeAll(() => {
mockDate = jest.spyOn(Date.prototype, 'toLocaleTimeString').mockReturnValue('2020-04-15');
});
afterAll(() => {
mockDate.mockRestore();
});
EDIT: I realised there's already a globalsetup.ts file in this project that is handling the timezone, so the problem is actually with the timestamp (AM, PM) and date format.
Upvotes: 1
Views: 2123
Reputation: 1336
We can change the default timezone of the Node.js runtime in the CLI by setting the TZ
environment variable. For more details, refer to the Node.js CLI documentation.
In my case, I used the cross-env
CLI to set the TZ
environment variable:
...
"test": "cross-env TZ=UTC jest"
...
Upvotes: 1
Reputation: 281
I ended up just needing to mock out the date and time functions.
jest
.spyOn(Date.prototype, 'toLocaleTimeString')
.mockImplementation(() => '12:00:00');
jest
.spyOn(Date.prototype, 'toLocaleDateString')
.mockImplementation(() => 'AM 1/01/2021');
Upvotes: 1
Reputation: 2167
When running jest at node (v12 and below), It doesn't have a full localization. you may want to install full-icu . Then you can just set your test script at package.json with something like
NODE_ICU_DATA=node_modules/full-icu jest
You may read the table describing that its not locale aware at this Node doc
Note that at Node 14
Its now comes with built in ICU. So if your app can run on v14. Go download v14 with nvm and try to run it again. If not go for full-icu to mock the localization support
Upvotes: 1