Skip to content

Commit

Permalink
feat(vitest): allow env to be stubbed to undefined (#6359)
Browse files Browse the repository at this point in the history
Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
  • Loading branch information
JSanchezIO and sheremet-va authored Sep 3, 2024
1 parent ad6e72f commit c3b2757
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
8 changes: 7 additions & 1 deletion docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ And while it is possible to spy on exports in `jsdom` or other Node.js environme

### vi.stubEnv {#vi-stubenv}

- **Type:** `(name: string, value: string) => Vitest`
- **Type:** `<T extends string>(name: T, value: T extends "PROD" | "DEV" | "SSR" ? boolean : string | undefined) => Vitest`

Changes the value of environmental variable on `process.env` and `import.meta.env`. You can restore its value by calling `vi.unstubAllEnvs`.

Expand All @@ -467,6 +467,12 @@ vi.stubEnv('NODE_ENV', 'production')

process.env.NODE_ENV === 'production'
import.meta.env.NODE_ENV === 'production'

vi.stubEnv('NODE_ENV', undefined)

process.env.NODE_ENV === undefined
import.meta.env.NODE_ENV === undefined

// doesn't change other envs
import.meta.env.MODE === 'development'
```
Expand Down
7 changes: 5 additions & 2 deletions packages/vitest/src/integrations/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ export interface VitestUtils {
*/
stubEnv: <T extends string>(
name: T,
value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string
value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string | undefined
) => VitestUtils

/**
Expand Down Expand Up @@ -642,13 +642,16 @@ function createVitest(): VitestUtils {
return utils
},

stubEnv(name: string, value: string | boolean) {
stubEnv(name: string, value: string | boolean | undefined) {
if (!_stubsEnv.has(name)) {
_stubsEnv.set(name, process.env[name])
}
if (_envBooleans.includes(name)) {
process.env[name] = value ? '1' : ''
}
else if (value === undefined) {
delete process.env[name]
}
else {
process.env[name] = String(value)
}
Expand Down
9 changes: 9 additions & 0 deletions test/core/test/stubs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,13 @@ describe('stubbing envs', () => {
vi.stubEnv('MY_TEST_ENV', true)
expect(import.meta.env.MY_TEST_ENV).toBe('true')
})

it('stubs to undefined and restores env', () => {
vi.stubEnv('VITE_TEST_UPDATE_ENV', undefined)
expect(import.meta.env.VITE_TEST_UPDATE_ENV).toBeUndefined()
expect(process.env.VITE_TEST_UPDATE_ENV).toBeUndefined()
vi.unstubAllEnvs()
expect(import.meta.env.VITE_TEST_UPDATE_ENV).toBe('development')
expect(process.env.VITE_TEST_UPDATE_ENV).toBe('development')
})
})

0 comments on commit c3b2757

Please sign in to comment.