[READ-ONLY] Mirror of https://github.com/vitest-dev/vitest. Next generation testing framework powered by Vite. vitest.dev
test testing-tools vite
12

Configure Feed

Select the types of activity you want to include in your feed.

fix(vitest): stubEnv casts boolean on PROD/SSR/DEV (#5590)

authored by

Vladimir and committed by
GitHub
(Apr 23, 2024, 10:01 AM +0200) 4da88045 2f0eee8e

+29 -3
+21
test/core/test/stubs.test.ts
··· 104 104 expect(import.meta.env.VITE_TEST_UPDATE_ENV).toBe('development') 105 105 expect(process.env.VITE_TEST_UPDATE_ENV).toBe('development') 106 106 }) 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 + }) 107 128 })
+8 -3
packages/vitest/src/integrations/vi.ts
··· 292 292 * Changes the value of `import.meta.env` and `process.env`. 293 293 * You can return it back to original value with `vi.unstubAllEnvs`, or by enabling `unstubEnvs` config option. 294 294 */ 295 - stubEnv: (name: string, value: string) => VitestUtils 295 + stubEnv: <T extends string>(name: T, value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string) => VitestUtils 296 296 297 297 /** 298 298 * Reset the value to original value that was available before first `vi.stubGlobal` was called. ··· 357 357 358 358 const _stubsGlobal = new Map<string | symbol | number, PropertyDescriptor | undefined>() 359 359 const _stubsEnv = new Map() 360 + 361 + const _envBooleans = ['PROD', 'DEV', 'SSR'] 360 362 361 363 const getImporter = () => { 362 364 const stackTrace = createSimpleStackTrace({ stackTraceLimit: 4 }) ··· 550 552 return utils 551 553 }, 552 554 553 - stubEnv(name: string, value: string) { 555 + stubEnv(name: string, value: string | boolean) { 554 556 if (!_stubsEnv.has(name)) 555 557 _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) 557 562 return utils 558 563 }, 559 564