|
1 | | -import { beforeEach, describe, expect, it } from 'vitest'; |
| 1 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
2 | 2 |
|
3 | | -import { readAndApplyEnvironmentVariables } from '../src/env.js'; |
| 3 | +import { readAndApplyEnvironmentVariables, readEnvironmentVariables } from '../src/env.js'; |
4 | 4 |
|
5 | | -describe('readAndApplyEnvironmentVariables()', () => { |
6 | | - beforeEach(() => { |
7 | | - process.env.WB_ENV = ''; |
8 | | - process.env.NODE_ENV = ''; |
9 | | - }); |
| 5 | +const originalEnv = { ...process.env }; |
| 6 | + |
| 7 | +beforeEach(() => { |
| 8 | + process.env.WB_ENV = ''; |
| 9 | + process.env.NODE_ENV = ''; |
| 10 | + // Clear env vars that could affect env loading behavior in tests. |
| 11 | + |
| 12 | + delete process.env.PORT; |
| 13 | + |
| 14 | + delete process.env.NAME; |
| 15 | +}); |
| 16 | + |
| 17 | +afterEach(() => { |
| 18 | + for (const key of Object.keys(process.env)) { |
| 19 | + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete |
| 20 | + delete process.env[key]; |
| 21 | + } |
| 22 | + Object.assign(process.env, originalEnv); |
| 23 | +}); |
10 | 24 |
|
| 25 | +describe('readAndApplyEnvironmentVariables()', () => { |
11 | 26 | it('should load no env vars with empty options', () => { |
12 | 27 | const envVars = readAndApplyEnvironmentVariables({}, 'test/fixtures/app1'); |
13 | 28 | expect(envVars).toEqual({}); |
@@ -44,4 +59,32 @@ describe('readAndApplyEnvironmentVariables()', () => { |
44 | 59 | ); |
45 | 60 | expect(envVars).toEqual({ ENV: 'test2', PORT: '4002', NAME: 'app2' }); |
46 | 61 | }); |
| 62 | + |
| 63 | + it('should not overwrite existing process.env values', () => { |
| 64 | + process.env.PORT = '9999'; |
| 65 | + process.env.NAME = 'override'; |
| 66 | + const envVars = readAndApplyEnvironmentVariables({ autoCascadeEnv: true }, 'test/fixtures/app1'); |
| 67 | + expect(envVars).toEqual({ ENV: 'development1' }); |
| 68 | + expect(process.env.ENV).toBe('development1'); |
| 69 | + expect(process.env.PORT).toBe('9999'); |
| 70 | + expect(process.env.NAME).toBe('override'); |
| 71 | + }); |
| 72 | +}); |
| 73 | + |
| 74 | +describe('readEnvironmentVariables()', () => { |
| 75 | + it('should skip existing process.env values in env vars and env files list', () => { |
| 76 | + process.env.PORT = '9999'; |
| 77 | + process.env.NAME = 'override'; |
| 78 | + const [envVars, envPathAndLoadedEnvVarNames] = readEnvironmentVariables( |
| 79 | + { autoCascadeEnv: true }, |
| 80 | + 'test/fixtures/app1' |
| 81 | + ); |
| 82 | + expect(envVars).toEqual({ ENV: 'development1' }); |
| 83 | + expect(envPathAndLoadedEnvVarNames).toEqual([ |
| 84 | + ['.env.development', ['ENV']], |
| 85 | + ['.env', []], |
| 86 | + ]); |
| 87 | + expect(process.env.PORT).toBe('9999'); |
| 88 | + expect(process.env.NAME).toBe('override'); |
| 89 | + }); |
47 | 90 | }); |
0 commit comments