I would like to set (actually mock) a timezone in my Vitest tests to get deterministic results in all time zones they will run in. I run my tests on a local machine and also in CI/CD environments that have different timezones.
I've searched for some answers on Stackoverflow but haven't found a good cleare way to do it in vitest.
Create a file vitest.global-setup.ts
export const setup = () => {
process.env.TZ = 'UTC'
}
Then add it to globalSetup in vitest.config.ts
export default defineConfig({
test: {
globalSetup: './vitest.global-setup.ts',
// ...
},
(Solution found in this GitHub comment)
If you want to manipulate the timezone per test:
beforeEach(() => {
vi.stubEnv('TZ', 'UTC');
});
afterEach(() => {
vi.unstubAllEnvs();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With