import { describe, it, expect, afterEach, vi } from 'vitest'; // env.ts reads process.env once at module-eval time, so each case re-imports it // under a controlled environment (resetModules busts the cached module), then // restores the original process.env immediately so nothing leaks to other tests. const KEYS = ['DATABASE_URL', 'BETTER_AUTH_SECRET', 'BETTER_AUTH_URL', 'PORT', 'CORS_ORIGINS']; async function loadEnv(overrides: Record) { const saved: Record = {}; for (const k of KEYS) saved[k] = process.env[k]; for (const k of KEYS) delete process.env[k]; for (const [k, v] of Object.entries(overrides)) if (v !== undefined) process.env[k] = v; vi.resetModules(); try { const { env } = await import('../src/env'); return env; } finally { for (const k of KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } } } describe('env', () => { afterEach(() => vi.resetModules()); it('applies every dev default when the vars are unset', async () => { const env = await loadEnv({}); expect(env.DATABASE_URL).toBe('file:./data/app.db'); expect(env.BETTER_AUTH_SECRET).toBe('dev-insecure-secret-change-me'); expect(env.BETTER_AUTH_URL).toBe('http://localhost:3000'); expect(env.PORT).toBe(3000); expect(env.WEB_ORIGINS).toEqual(['http://localhost:5173', 'http://localhost:5174']); }); it('reads each override when the var is set (PORT coerced to a number)', async () => { const env = await loadEnv({ DATABASE_URL: 'file:./other.db', BETTER_AUTH_SECRET: 'top-secret', BETTER_AUTH_URL: 'https://api.example.com', PORT: '8080', }); expect(env.DATABASE_URL).toBe('file:./other.db'); expect(env.BETTER_AUTH_SECRET).toBe('top-secret'); expect(env.BETTER_AUTH_URL).toBe('https://api.example.com'); expect(env.PORT).toBe(8080); expect(typeof env.PORT).toBe('number'); }); it('parses CORS_ORIGINS into WEB_ORIGINS, trimming and dropping empty entries', async () => { const env = await loadEnv({ CORS_ORIGINS: ' http://a.example , http://b.example , ' }); expect(env.WEB_ORIGINS).toEqual(['http://a.example', 'http://b.example']); }); it('falls back to the default origins when CORS_ORIGINS is empty', async () => { const env = await loadEnv({ CORS_ORIGINS: '' }); expect(env.WEB_ORIGINS).toEqual(['http://localhost:5173', 'http://localhost:5174']); }); });