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.
Looks like you should use vi.stubEnv instead.
vi.stubEnvType: (name: string, value: string) => VitestChanges the value of environmental variable onprocess.envandimport.meta.env. You can restore its value by callingvi.unstubAllEnvs.
So use this:
import { vi } from 'vitest'
beforeAll(() => {
vi.stubEnv('HASHNODE_URL', 'https://blog.IgorKrpenja.com')
});
afterAll(() => {
vi.unstubAllEnvs();
});
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
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