Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a timezone in vitest

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.

like image 945
Chen Peleg Avatar asked Feb 01 '26 08:02

Chen Peleg


2 Answers

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)

like image 165
Simon Tran Avatar answered Feb 04 '26 00:02

Simon Tran


If you want to manipulate the timezone per test:

beforeEach(() => {
  vi.stubEnv('TZ', 'UTC');
});

afterEach(() => {
  vi.unstubAllEnvs();
});
like image 40
Jasha Avatar answered Feb 03 '26 23:02

Jasha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!