diff --git a/packages/vitest/src/integrations/vi.ts b/packages/vitest/src/integrations/vi.ts index f37dbd3a0c91..478bcff9ff70 100644 --- a/packages/vitest/src/integrations/vi.ts +++ b/packages/vitest/src/integrations/vi.ts @@ -292,7 +292,7 @@ export interface VitestUtils { * Changes the value of `import.meta.env` and `process.env`. * You can return it back to original value with `vi.unstubAllEnvs`, or by enabling `unstubEnvs` config option. */ - stubEnv: (name: string, value: string) => VitestUtils + stubEnv: (name: T, value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string) => VitestUtils /** * Reset the value to original value that was available before first `vi.stubGlobal` was called. @@ -358,6 +358,8 @@ function createVitest(): VitestUtils { const _stubsGlobal = new Map() const _stubsEnv = new Map() + const _envBooleans = ['PROD', 'DEV', 'SSR'] + const getImporter = () => { const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 }) const importerStack = stackTrace.split('\n')[4] @@ -550,10 +552,13 @@ function createVitest(): VitestUtils { return utils }, - stubEnv(name: string, value: string) { + stubEnv(name: string, value: string | boolean) { if (!_stubsEnv.has(name)) _stubsEnv.set(name, process.env[name]) - process.env[name] = value + if (_envBooleans.includes(name)) + process.env[name] = value ? '1' : '' + else + process.env[name] = String(value) return utils }, diff --git a/test/core/test/stubs.test.ts b/test/core/test/stubs.test.ts index 9ee8c3a96669..47e5005e952d 100644 --- a/test/core/test/stubs.test.ts +++ b/test/core/test/stubs.test.ts @@ -104,4 +104,25 @@ describe('stubbing envs', () => { expect(import.meta.env.VITE_TEST_UPDATE_ENV).toBe('development') expect(process.env.VITE_TEST_UPDATE_ENV).toBe('development') }) + + it.each(['PROD', 'DEV', 'SSR'] as const)('requires boolean for env.%s', (name) => { + vi.stubEnv(name as 'PROD', false) + expect(import.meta.env[name]).toBe(false) + expect(process.env[name]).toBe('') + + vi.stubEnv(name as 'PROD', true) + expect(import.meta.env[name]).toBe(true) + expect(process.env[name]).toBe('1') + + // @ts-expect-error PROD, DEV, SSR expect a boolean + vi.stubEnv(name as 'PROD', 'string') + // @ts-expect-error PROD, DEV, SSR expect a boolean + vi.stubEnv(name, 'string') + }) + + it('setting boolean casts the value to string', () => { + // @ts-expect-error value should be a string + vi.stubEnv('MY_TEST_ENV', true) + expect(import.meta.env.MY_TEST_ENV).toBe('true') + }) })