Configure Timezone for Jest/Node.js with the `TZ` env var
In order to test code that involves date and time manipulation and parsing. It can be useful to set the timezone under which the Jest tests run.
Thankfully Node.js supports the TZ
environment variable: “The TZ environment variable is used to specify the timezone configuration.” (Node.js docs).
Table of Contents
Why set a timezone for tests?
By default Node.js and therefore Jest will use the local timezone of the machine they’re being run on. This can cause issues if:
- Developers are in different timezones (or if their machine is configured for different timezones)
- Local vs CI/CD consistency, similarly CI/CD will usually default to UTC, which can cause problems if that’s not the case for developers locally
- Testing logic that is affected by timezones, in this case it can be useful to run the tests in multiple timezones
Next, we’ll now see how to set the timezone using the TZ
environment variable.
Setting the Timezone Using the TZ
Environment Variable
The TZ
environment variable allows you to specify the timezone for your tests. This is especially useful for date and time manipulation, ensuring that your tests behave consistently regardless of the environment.
Here’s how you can set the TZ
environment variable in your Jest configuration:
If you use "test"
npm script, You can set the TZ
variable directly in the scripts
section of your package.json
.
{
"scripts": {
"test": "TZ=UTC jest"
}
}
Note: in order for this to work on Windows, we should use the cross-env
package:
npm i --save-dev cross-env
update your
package.json
:{ "scripts": { "test": "cross-env TZ=UTC jest" } }
You can test in different timezones by setting a different TZ value, for example:
{
"scripts": {
"test": "cross-env TZ=UTC jest",
"test:tz": "cross-env TZ=America/New_York jest"
}
}
See the reference list of values the timezone id/TZ
env var can take: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones.
Conclusion
Setting the timezone via the TZ
environment variable is useful to avoid test failures due to different configured timezones in development and CI/CD machines. The TZ
environment variable can also be used to run a set of tests in multiple timezones.
Another key skill for testing datetime-sensitive code is to mock the current date, for which there is a guide at Mocking/stubbing the current Date in Jest tests.
Get The Jest Handbook (100 pages)
Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.
orJoin 1000s of developers learning about Enterprise-grade Node.js & JavaScript