Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking .env variables with Vitest

I want to mock env variables with Vitest. For now, I was able to do it this way:

// test
beforeAll(() => {
  import.meta.env.HASHNODE_URL = 'https://blog.IgorKrpenja.com';
});

// tested function using an env variable
export const getCanonicalUrl = (slug: string): string => {
  return `${process.env.HASHNODE_URL}/${slug}`;
};

However, this a bit cumbersome as I would need to do this in every test suite for the same env variables.

I also tried using setup files this way but it didn't work:

// vitest.config.ts
/// <reference types="vitest" />

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    setupFiles: ['./test/env-mock.ts'],
  },
});
 
// test/env-mock.ts
beforeAll(() => {
  import.meta.env.HASHNODE_URL = 'https://blog.IgorKrpenja.com';
});

afterAll(() => {
  delete import.meta.env.HASHNODE_URL;
});

And could not get this to work with globalSetup either:

// In same vitest.config.ts
globalSetup: './test/global-setup.ts',

// test/global-setup.ts
export function setup(): void {
  import.meta.env.HASHNODE_URL = 'https://blog.IgorKrpenja.com';
}

export function teardown(): void {}

Any ideas? This is with Typescript Node.js project, Vitest 0.33.0.

like image 329
Igor Avatar asked Sep 02 '26 17:09

Igor


2 Answers

Looks like you should use vi.stubEnv instead.

vi.stubEnv Type: (name: string, value: string) => Vitest Changes the value of environmental variable on process.env and import.meta.env. You can restore its value by calling vi.unstubAllEnvs.

So use this:

import { vi } from 'vitest'

beforeAll(() => {
  vi.stubEnv('HASHNODE_URL', 'https://blog.IgorKrpenja.com')
});

afterAll(() => {
  vi.unstubAllEnvs();
});
like image 50
chonz0 Avatar answered Sep 04 '26 06:09

chonz0


In the vitest config file vitest.config.ts, you can add a define object inside defineConfig like so:

define: {
  'import.meta.env.ENV_VARIABLE': JSON.stringify(process.env.ENV_VARIABLE)
}

This way, you don't have to define the variable in every test file.

https://vitejs.dev/config/shared-options.html#envprefix

like image 27
Berry Avatar answered Sep 04 '26 06:09

Berry



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!