|
| 1 | +import { IsBooleanString, IsDate, IsNumber, IsString } from 'class-validator'; |
| 2 | +import { TestContainer } from '../testing/container'; |
| 3 | +import { EnvModuleMixin } from './env.module-mixin'; |
| 4 | + |
| 5 | +describe('registration', () => { |
| 6 | + class Env { |
| 7 | + @IsString() |
| 8 | + SOME_STRING: string; |
| 9 | + } |
| 10 | + class EnvModule extends EnvModuleMixin<Env>(Env) {} |
| 11 | + |
| 12 | + it('should properly load the environment variables and module', async () => { |
| 13 | + vi.stubEnv('SOME_STRING', 'foo'); |
| 14 | + const container = await TestContainer.create({ |
| 15 | + imports: [EnvModule], |
| 16 | + }); |
| 17 | + const module = container.module.get<EnvModule>(EnvModule); |
| 18 | + expect(module).toBeDefined(); |
| 19 | + expect(EnvModule.get('SOME_STRING')).toBe('foo'); |
| 20 | + }); |
| 21 | +}); |
| 22 | + |
| 23 | +describe('validation', () => { |
| 24 | + it('should throw an error due to a missing environment variable', () => { |
| 25 | + vi.unstubAllEnvs(); |
| 26 | + class Env { |
| 27 | + @IsString() |
| 28 | + SOME_STRING: string; |
| 29 | + } |
| 30 | + class EnvModule extends EnvModuleMixin<Env>(Env) {} |
| 31 | + expect( |
| 32 | + TestContainer.create({ |
| 33 | + imports: [EnvModule], |
| 34 | + }), |
| 35 | + ).rejects.toThrowError(`An instance of Env has failed the validation: |
| 36 | + - property SOME_STRING has failed the following constraints: isString`); |
| 37 | + }); |
| 38 | + |
| 39 | + it('should throw an error due to a type mismatch', () => { |
| 40 | + vi.stubEnv('SOME_BOOLEAN', 'foo'); |
| 41 | + class Env { |
| 42 | + @IsBooleanString() |
| 43 | + SOME_BOOLEAN: 'true' | 'false'; |
| 44 | + } |
| 45 | + class EnvModule extends EnvModuleMixin<Env>(Env) {} |
| 46 | + expect( |
| 47 | + TestContainer.create({ |
| 48 | + imports: [EnvModule], |
| 49 | + }), |
| 50 | + ).rejects.toThrowError(`An instance of Env has failed the validation: |
| 51 | + - property SOME_BOOLEAN has failed the following constraints: isBooleanString`); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should implicitly perform certain conversions', async () => { |
| 55 | + vi.stubEnv('SOME_DATE', '2024-08-13T17:34:00Z'); |
| 56 | + vi.stubEnv('SOME_NUMBER', '123'); |
| 57 | + class Env { |
| 58 | + @IsDate() |
| 59 | + SOME_DATE: Date; |
| 60 | + @IsNumber() |
| 61 | + SOME_NUMBER: number; |
| 62 | + } |
| 63 | + class EnvModule extends EnvModuleMixin<Env>(Env) {} |
| 64 | + await TestContainer.create({ |
| 65 | + imports: [EnvModule], |
| 66 | + }); |
| 67 | + expect(EnvModule.get('SOME_DATE')).toEqual(new Date('2024-08-13T17:34:00Z')); |
| 68 | + expect(EnvModule.get('SOME_NUMBER')).toBe(123); |
| 69 | + }); |
| 70 | +}); |
| 71 | + |
| 72 | +describe('decorators', () => { |
| 73 | + it('should work with decorators', () => { |
| 74 | + vi.stubEnv('HELLO_ROUTE', '/hello'); |
| 75 | + }); |
| 76 | +}); |
0 commit comments