EnvModel: Returns error if environment not set (translated errors)
Overview
These tests validate nestjs-mod EnvModel: environment variable reading, required field validation, and DI value propagation into services.
What We Do And Verify
-
We verify how
envTransformandEnvModel/EnvModelPropertydecorators extract and validate env values. -
We confirm expected behavior for missing or invalid required env fields.
-
We lock the DI access contract for env values in services.
-
We lock the API boundary contract (status, payload, and response shape) to protect externally observable behavior.
-
We explicitly validate the error contract: not only failure itself, but also error shape/content expected by module consumers.
-
We confirm correct lifecycle behavior in test environment: initialization, dependency readiness, and graceful shutdown of app/modules.
GitHub Reference
- File: sample-with-shared-config.controller.spec.ts
- Line: 33
Setup Code
import {
import { DefaultTestNestApplicationCreate, DefaultTestNestApplicationInitializer } from '@nestjs-mod/testing';
import { Controller, Get, Injectable, Module } from '@nestjs/common';
import { IsNotEmpty, setClassValidatorMessages } from 'class-validator-multi-lang';
import { readFileSync } from 'fs';
import { resolve } from 'path';
import request from 'supertest';
import { SampleWithSharedConfig } from './sample-with-shared-config.module';
import { SampleWithSharedConfigService } from './sample-with-shared-config.service';
describe('SampleWithSharedConfigController', () => {
// full test in the block below
});
Test Code
it('should return error if environment not set (translated errors)', async () => {
const RU_I18N_MESSAGES = JSON.parse(
readFileSync(
resolve(__dirname, '../../../../../node_modules/class-validator-multi-lang/i18n/ru.json'),
).toString(),
);
setClassValidatorMessages(RU_I18N_MESSAGES);
const TEST_APP_NAME = 'TestAppModule';
@EnvModel({ name: TEST_APP_NAME })
class TestAppEnvironments {
@EnvModelProperty()
@IsNotEmpty()
var1!: string;
}
const { TestAppModule } = createNestModule({
moduleName: TEST_APP_NAME,
moduleCategory: NestModuleCategory.feature,
staticEnvironmentsModel: TestAppEnvironments,
environmentsOptions: {
validatorPackage: require('class-validator-multi-lang'),
},
});
await expect(
bootstrapNestApplication({
project: {
name: 'TestApplication',
description: 'Test application',
},
modules: {
system: [DefaultTestNestApplicationCreate.forRoot(), DefaultTestNestApplicationInitializer.forRoot()],
feature: [TestAppModule.forRoot()],
},
}),
).rejects.toHaveProperty('errors.0.constraints.isNotEmpty', 'var1 не может быть пустым');
});