Skip to content

Commit 4da8804

Browse files
authored
fix(vitest): stubEnv casts boolean on PROD/SSR/DEV (#5590)
1 parent 2f0eee8 commit 4da8804

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

packages/vitest/src/integrations/vi.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ export interface VitestUtils {
292292
* Changes the value of `import.meta.env` and `process.env`.
293293
* You can return it back to original value with `vi.unstubAllEnvs`, or by enabling `unstubEnvs` config option.
294294
*/
295-
stubEnv: (name: string, value: string) => VitestUtils
295+
stubEnv: <T extends string>(name: T, value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string) => VitestUtils
296296

297297
/**
298298
* Reset the value to original value that was available before first `vi.stubGlobal` was called.
@@ -358,6 +358,8 @@ function createVitest(): VitestUtils {
358358
const _stubsGlobal = new Map<string | symbol | number, PropertyDescriptor | undefined>()
359359
const _stubsEnv = new Map()
360360

361+
const _envBooleans = ['PROD', 'DEV', 'SSR']
362+
361363
const getImporter = () => {
362364
const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 })
363365
const importerStack = stackTrace.split('\n')[4]
@@ -550,10 +552,13 @@ function createVitest(): VitestUtils {
550552
return utils
551553
},
552554

553-
stubEnv(name: string, value: string) {
555+
stubEnv(name: string, value: string | boolean) {
554556
if (!_stubsEnv.has(name))
555557
_stubsEnv.set(name, process.env[name])
556-
process.env[name] = value
558+
if (_envBooleans.includes(name))
559+
process.env[name] = value ? '1' : ''
560+
else
561+
process.env[name] = String(value)
557562
return utils
558563
},
559564

test/core/test/stubs.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,25 @@ describe('stubbing envs', () => {
104104
expect(import.meta.env.VITE_TEST_UPDATE_ENV).toBe('development')
105105
expect(process.env.VITE_TEST_UPDATE_ENV).toBe('development')
106106
})
107+
108+
it.each(['PROD', 'DEV', 'SSR'] as const)('requires boolean for env.%s', (name) => {
109+
vi.stubEnv(name as 'PROD', false)
110+
expect(import.meta.env[name]).toBe(false)
111+
expect(process.env[name]).toBe('')
112+
113+
vi.stubEnv(name as 'PROD', true)
114+
expect(import.meta.env[name]).toBe(true)
115+
expect(process.env[name]).toBe('1')
116+
117+
// @ts-expect-error PROD, DEV, SSR expect a boolean
118+
vi.stubEnv(name as 'PROD', 'string')
119+
// @ts-expect-error PROD, DEV, SSR expect a boolean
120+
vi.stubEnv(name, 'string')
121+
})
122+
123+
it('setting boolean casts the value to string', () => {
124+
// @ts-expect-error value should be a string
125+
vi.stubEnv('MY_TEST_ENV', true)
126+
expect(import.meta.env.MY_TEST_ENV).toBe('true')
127+
})
107128
})

0 commit comments

Comments
 (0)