|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | + |
| 3 | +vi.mock('../common/../configs', () => ({ |
| 4 | + validationResult: { success: true }, |
| 5 | +})); |
| 6 | + |
| 7 | +import * as configs from '../common/../configs'; |
| 8 | +import { validateEnv } from '../common/utils'; |
| 9 | + |
| 10 | +type ValidationResult = { |
| 11 | + success: boolean; |
| 12 | + error?: { issues: { path: unknown[]; message: string }[] }; |
| 13 | +}; |
| 14 | +function setValidationResult(result: ValidationResult) { |
| 15 | + (configs as { validationResult: ValidationResult }).validationResult = result; |
| 16 | +} |
| 17 | + |
| 18 | +describe('validateEnv', () => { |
| 19 | + let errorSpy: ReturnType<typeof vi.spyOn>; |
| 20 | + let exitSpy: ReturnType<typeof vi.spyOn>; |
| 21 | + |
| 22 | + beforeEach(() => { |
| 23 | + errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 24 | + exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { |
| 25 | + throw new Error('exit'); |
| 26 | + }) as unknown as ReturnType<typeof vi.spyOn>; |
| 27 | + }); |
| 28 | + |
| 29 | + afterEach(() => { |
| 30 | + errorSpy.mockRestore(); |
| 31 | + exitSpy.mockRestore(); |
| 32 | + }); |
| 33 | + |
| 34 | + it('does nothing if validationResult.success is true', () => { |
| 35 | + setValidationResult({ success: true }); |
| 36 | + expect(() => validateEnv()).not.toThrow(); |
| 37 | + expect(errorSpy).not.toHaveBeenCalled(); |
| 38 | + expect(exitSpy).not.toHaveBeenCalled(); |
| 39 | + }); |
| 40 | + |
| 41 | + it('logs error and exits if validationResult.success is false', () => { |
| 42 | + setValidationResult({ |
| 43 | + success: false, |
| 44 | + error: { |
| 45 | + issues: [ |
| 46 | + { path: ['FOO'], message: 'is required' }, |
| 47 | + { path: [], message: 'unknown' }, |
| 48 | + ], |
| 49 | + }, |
| 50 | + }); |
| 51 | + expect(() => validateEnv()).toThrow('exit'); |
| 52 | + expect(errorSpy).toHaveBeenCalledWith( |
| 53 | + 'Missing or invalid environment variable: FOO (is required)\n' + |
| 54 | + 'Missing or invalid environment variable: (unknown variable) (unknown)', |
| 55 | + ); |
| 56 | + expect(exitSpy).toHaveBeenCalledWith(1); |
| 57 | + }); |
| 58 | +}); |
0 commit comments