Skip to content

Commit

Permalink
fix(vitest): stubEnv casts boolean on PROD/SSR/DEV (#5590)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Apr 23, 2024
1 parent 2f0eee8 commit 4da8804
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/vitest/src/integrations/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: <T extends string>(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.
Expand Down Expand Up @@ -358,6 +358,8 @@ function createVitest(): VitestUtils {
const _stubsGlobal = new Map<string | symbol | number, PropertyDescriptor | undefined>()
const _stubsEnv = new Map()

const _envBooleans = ['PROD', 'DEV', 'SSR']

const getImporter = () => {
const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 })
const importerStack = stackTrace.split('\n')[4]
Expand Down Expand Up @@ -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
},

Expand Down
21 changes: 21 additions & 0 deletions test/core/test/stubs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})

0 comments on commit 4da8804

Please sign in to comment.