node.js health api request test fails by zod validation?

I have a Node.js Express application that I’m trying to test using vitest and supertest. However, I’m encountering issues with missing environment variables. Here’s my setup:

Environment Configuration (environment.ts):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import z from 'zod';
const envSchema = z.object({
HOST: z
.string()
.trim()
.refine(
host => host.startsWith('http') || host.startsWith('https'),
'Invalid URL format',
),
PORT: z.coerce
.number({
description:
'.env files convert numbers to strings, therefore we have to enforce them to be numbers',
})
.positive()
.max(65536, `options.port should be >= 0 and < 65536`)
.default(3000),
BASE_URL: z.string().trim().min(1).default('/api/v1'),
DATABASE_URL: z
.string()
.url()
.trim()
.refine(url => url.startsWith('mongodb://'), 'Invalid Database URL format'),
GITHUB_API_URL: z
.string()
.url()
.trim()
.refine(url => url.startsWith('https://'), 'Invalid Github URL format')
.default('https://api.github.com'),
GITHUB_SECRET: z.string().trim().min(1),
LOG_DIR: z.string().optional(),
CLIENT_URL: z
.string()
.url()
.trim()
.refine(url => url.startsWith('http://'), 'Invalid client URL format')
.default('http://localhost:5173/'),
CORS_ORIGIN: z.string().trim().min(1).default('*'),
CORS_CREDENTIALS: z.boolean().default(true),
NODE_ENV: z
.enum(['development', 'production', 'test'])
.default('development'),
});
const envServer = envSchema.safeParse({
HOST: process.env.HOST,
PORT: process.env.PORT,
BASE_URL: process.env.BASE_URL,
DATABASE_URL: process.env.DATABASE_URL,
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: process.env.REDIS_PORT,
REDIS_TTL: process.env.REDIS_TTL,
REDIS_TIMEOUT: process.env.REDIS_TIMEOUT,
GITHUB_API_URL: process.env.GITHUB_API_URL,
GITHUB_SECRET: process.env.GITHUB_SECRET,
LOG_DIR: process.env.LOG_DIR,
CLIENT_URL: process.env.CLIENT_URL,
CORS_ORIGIN: process.env.CORS_ORIGIN,
CORS_CREDENTIALS: process.env.CORS_CREDENTIALS,
NODE_ENV: process.env.NODE_ENV,
});
if (!envServer.success) {
console.error(envServer.error.issues);
throw new Error('There is an error with the server environment variables');
}
export const serverSchema = envServer.data;
</code>
<code>import z from 'zod'; const envSchema = z.object({ HOST: z .string() .trim() .refine( host => host.startsWith('http') || host.startsWith('https'), 'Invalid URL format', ), PORT: z.coerce .number({ description: '.env files convert numbers to strings, therefore we have to enforce them to be numbers', }) .positive() .max(65536, `options.port should be >= 0 and < 65536`) .default(3000), BASE_URL: z.string().trim().min(1).default('/api/v1'), DATABASE_URL: z .string() .url() .trim() .refine(url => url.startsWith('mongodb://'), 'Invalid Database URL format'), GITHUB_API_URL: z .string() .url() .trim() .refine(url => url.startsWith('https://'), 'Invalid Github URL format') .default('https://api.github.com'), GITHUB_SECRET: z.string().trim().min(1), LOG_DIR: z.string().optional(), CLIENT_URL: z .string() .url() .trim() .refine(url => url.startsWith('http://'), 'Invalid client URL format') .default('http://localhost:5173/'), CORS_ORIGIN: z.string().trim().min(1).default('*'), CORS_CREDENTIALS: z.boolean().default(true), NODE_ENV: z .enum(['development', 'production', 'test']) .default('development'), }); const envServer = envSchema.safeParse({ HOST: process.env.HOST, PORT: process.env.PORT, BASE_URL: process.env.BASE_URL, DATABASE_URL: process.env.DATABASE_URL, REDIS_HOST: process.env.REDIS_HOST, REDIS_PORT: process.env.REDIS_PORT, REDIS_TTL: process.env.REDIS_TTL, REDIS_TIMEOUT: process.env.REDIS_TIMEOUT, GITHUB_API_URL: process.env.GITHUB_API_URL, GITHUB_SECRET: process.env.GITHUB_SECRET, LOG_DIR: process.env.LOG_DIR, CLIENT_URL: process.env.CLIENT_URL, CORS_ORIGIN: process.env.CORS_ORIGIN, CORS_CREDENTIALS: process.env.CORS_CREDENTIALS, NODE_ENV: process.env.NODE_ENV, }); if (!envServer.success) { console.error(envServer.error.issues); throw new Error('There is an error with the server environment variables'); } export const serverSchema = envServer.data; </code>
import z from 'zod';

const envSchema = z.object({
  HOST: z
    .string()
    .trim()
    .refine(
      host => host.startsWith('http') || host.startsWith('https'),
      'Invalid URL format',
    ),
  PORT: z.coerce
    .number({
      description:
        '.env files convert numbers to strings, therefore we have to enforce them to be numbers',
    })
    .positive()
    .max(65536, `options.port should be >= 0 and < 65536`)
    .default(3000),
  BASE_URL: z.string().trim().min(1).default('/api/v1'),
  DATABASE_URL: z
    .string()
    .url()
    .trim()
    .refine(url => url.startsWith('mongodb://'), 'Invalid Database URL format'),
  GITHUB_API_URL: z
    .string()
    .url()
    .trim()
    .refine(url => url.startsWith('https://'), 'Invalid Github URL format')
    .default('https://api.github.com'),
  GITHUB_SECRET: z.string().trim().min(1),
  LOG_DIR: z.string().optional(),
  CLIENT_URL: z
    .string()
    .url()
    .trim()
    .refine(url => url.startsWith('http://'), 'Invalid client URL format')
    .default('http://localhost:5173/'),
  CORS_ORIGIN: z.string().trim().min(1).default('*'),
  CORS_CREDENTIALS: z.boolean().default(true),
  NODE_ENV: z
    .enum(['development', 'production', 'test'])
    .default('development'),
});

const envServer = envSchema.safeParse({
  HOST: process.env.HOST,
  PORT: process.env.PORT,
  BASE_URL: process.env.BASE_URL,
  DATABASE_URL: process.env.DATABASE_URL,
  REDIS_HOST: process.env.REDIS_HOST,
  REDIS_PORT: process.env.REDIS_PORT,
  REDIS_TTL: process.env.REDIS_TTL,
  REDIS_TIMEOUT: process.env.REDIS_TIMEOUT,
  GITHUB_API_URL: process.env.GITHUB_API_URL,
  GITHUB_SECRET: process.env.GITHUB_SECRET,
  LOG_DIR: process.env.LOG_DIR,
  CLIENT_URL: process.env.CLIENT_URL,
  CORS_ORIGIN: process.env.CORS_ORIGIN,
  CORS_CREDENTIALS: process.env.CORS_CREDENTIALS,
  NODE_ENV: process.env.NODE_ENV,
});

if (!envServer.success) {
  console.error(envServer.error.issues);
  throw new Error('There is an error with the server environment variables');
}

export const serverSchema = envServer.data;

Server Setup (server.ts):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import { Application, json, urlencoded } from 'express';
import helmet from 'helmet';
import hpp from 'hpp';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import { ErrorMiddleware } from '@/libs/shared/middlewares/error.middleware';
import logger from '@/utils/logger';
import { MongoDBInstance as dbConnection } from '@/config/database';
import { serverSchema } from '@/config/environment';
import applicationRoutes from '@/routes/index';
export class Server {
private readonly app: Application;
constructor(app: Application) {
this.app = app;
}
public start(): void {
this.connectDatabase();
this.securityMiddleware(this.app);
this.routesMiddleware(this.app);
this.globalErrorHandler(this.app);
this.startServer(this.app);
this.initializeSwagger();
}
public getServer() {
return this.app;
}
private securityMiddleware(app: Application): void {
app.use(hpp());
app.use(helmet());
app.use(compression());
app.use(json());
app.use(urlencoded({ extended: true, limit: '50mb' }));
app.use(cookieParser());
app.use(
cors({
origin: serverSchema.CLIENT_URL,
credentials: serverSchema.CORS_CREDENTIALS,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
}),
);
}
private routesMiddleware(app: Application): void {
applicationRoutes(app);
}
private globalErrorHandler(app: Application): void {
app.use(ErrorMiddleware);
}
private connectDatabase(): void {
dbConnection.getInstance();
}
private startServer(app: Application): void {
logger.info(`------ NODE_ENV: ${serverSchema.NODE_ENV} ------`);
logger.info(`Server has started with process ${process.pid}`);
app.listen(serverSchema.PORT, () => {
logger.info(`Server listening on port ${serverSchema.PORT}`);
});
}
private initializeSwagger() {
const options = {
swaggerDefinition: {
openapi: '3.0.3',
info: {
title: 'API Documentation',
version: '1.0.0',
description: 'REST API docs',
},
servers: [
{
url: `${serverSchema.HOST}:${serverSchema.PORT}${serverSchema.BASE_URL}`,
},
],
},
apis: ['./swagger.yaml'],
};
const swaggerSpecs = swaggerJSDoc(options);
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecs));
logger.info(
`Docs are available at ${serverSchema.HOST}:${serverSchema.PORT}/api-docs`,
);
}
}
</code>
<code> import compression from 'compression'; import cookieParser from 'cookie-parser'; import cors from 'cors'; import { Application, json, urlencoded } from 'express'; import helmet from 'helmet'; import hpp from 'hpp'; import swaggerJSDoc from 'swagger-jsdoc'; import swaggerUi from 'swagger-ui-express'; import { ErrorMiddleware } from '@/libs/shared/middlewares/error.middleware'; import logger from '@/utils/logger'; import { MongoDBInstance as dbConnection } from '@/config/database'; import { serverSchema } from '@/config/environment'; import applicationRoutes from '@/routes/index'; export class Server { private readonly app: Application; constructor(app: Application) { this.app = app; } public start(): void { this.connectDatabase(); this.securityMiddleware(this.app); this.routesMiddleware(this.app); this.globalErrorHandler(this.app); this.startServer(this.app); this.initializeSwagger(); } public getServer() { return this.app; } private securityMiddleware(app: Application): void { app.use(hpp()); app.use(helmet()); app.use(compression()); app.use(json()); app.use(urlencoded({ extended: true, limit: '50mb' })); app.use(cookieParser()); app.use( cors({ origin: serverSchema.CLIENT_URL, credentials: serverSchema.CORS_CREDENTIALS, optionsSuccessStatus: 200, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], }), ); } private routesMiddleware(app: Application): void { applicationRoutes(app); } private globalErrorHandler(app: Application): void { app.use(ErrorMiddleware); } private connectDatabase(): void { dbConnection.getInstance(); } private startServer(app: Application): void { logger.info(`------ NODE_ENV: ${serverSchema.NODE_ENV} ------`); logger.info(`Server has started with process ${process.pid}`); app.listen(serverSchema.PORT, () => { logger.info(`Server listening on port ${serverSchema.PORT}`); }); } private initializeSwagger() { const options = { swaggerDefinition: { openapi: '3.0.3', info: { title: 'API Documentation', version: '1.0.0', description: 'REST API docs', }, servers: [ { url: `${serverSchema.HOST}:${serverSchema.PORT}${serverSchema.BASE_URL}`, }, ], }, apis: ['./swagger.yaml'], }; const swaggerSpecs = swaggerJSDoc(options); this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecs)); logger.info( `Docs are available at ${serverSchema.HOST}:${serverSchema.PORT}/api-docs`, ); } } </code>

import compression from 'compression';
import cookieParser from 'cookie-parser';
import cors from 'cors';
import { Application, json, urlencoded } from 'express';
import helmet from 'helmet';
import hpp from 'hpp';
import swaggerJSDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';

import { ErrorMiddleware } from '@/libs/shared/middlewares/error.middleware';

import logger from '@/utils/logger';

import { MongoDBInstance as dbConnection } from '@/config/database';
import { serverSchema } from '@/config/environment';

import applicationRoutes from '@/routes/index';

export class Server {
  private readonly app: Application;

  constructor(app: Application) {
    this.app = app;
  }

  public start(): void {
    this.connectDatabase();
    this.securityMiddleware(this.app);
    this.routesMiddleware(this.app);
    this.globalErrorHandler(this.app);
    this.startServer(this.app);
    this.initializeSwagger();
  }

  public getServer() {
    return this.app;
  }

  private securityMiddleware(app: Application): void {
    app.use(hpp());
    app.use(helmet());
    app.use(compression());
    app.use(json());
    app.use(urlencoded({ extended: true, limit: '50mb' }));
    app.use(cookieParser());
    app.use(
      cors({
        origin: serverSchema.CLIENT_URL,
        credentials: serverSchema.CORS_CREDENTIALS,
        optionsSuccessStatus: 200,
        methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
      }),
    );
  }

  private routesMiddleware(app: Application): void {
    applicationRoutes(app);
  }

  private globalErrorHandler(app: Application): void {
    app.use(ErrorMiddleware);
  }

  private connectDatabase(): void {
    dbConnection.getInstance();
  }

  private startServer(app: Application): void {
    logger.info(`------ NODE_ENV: ${serverSchema.NODE_ENV} ------`);
    logger.info(`Server has started with process ${process.pid}`);
    app.listen(serverSchema.PORT, () => {
      logger.info(`Server listening on port ${serverSchema.PORT}`);
    });
  }

  private initializeSwagger() {
    const options = {
      swaggerDefinition: {
        openapi: '3.0.3',
        info: {
          title: 'API Documentation',
          version: '1.0.0',
          description: 'REST API docs',
        },
        servers: [
          {
            url: `${serverSchema.HOST}:${serverSchema.PORT}${serverSchema.BASE_URL}`,
          },
        ],
      },
      apis: ['./swagger.yaml'],
    };

    const swaggerSpecs = swaggerJSDoc(options);
    this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecs));

    logger.info(
      `Docs are available at ${serverSchema.HOST}:${serverSchema.PORT}/api-docs`,
    );
  }
}

Health Controller (health.controller.ts):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express, { Application } from 'express';
import request from 'supertest';
import { beforeAll, describe, expect, it } from 'vitest';
import HealthController from '@/controllers/health.controller';
import { Server } from '@/server';
describe('HealthController', () => {
let app: Application;
beforeAll(() => {
app = new Server(express()).getServer();
const controller = new HealthController();
app.get('/health', controller.getHealth);
});
it('GET /health should return status 200 and { health: "OK!" } when GET /health', async () => {
const response = await request(app).get('/health');
expect(response.status).toEqual(200);
expect(response.body).toEqual({ health: 'OK!' });
});
});
</code>
<code>import express, { Application } from 'express'; import request from 'supertest'; import { beforeAll, describe, expect, it } from 'vitest'; import HealthController from '@/controllers/health.controller'; import { Server } from '@/server'; describe('HealthController', () => { let app: Application; beforeAll(() => { app = new Server(express()).getServer(); const controller = new HealthController(); app.get('/health', controller.getHealth); }); it('GET /health should return status 200 and { health: "OK!" } when GET /health', async () => { const response = await request(app).get('/health'); expect(response.status).toEqual(200); expect(response.body).toEqual({ health: 'OK!' }); }); }); </code>
import express, { Application } from 'express';
import request from 'supertest';
import { beforeAll, describe, expect, it } from 'vitest';

import HealthController from '@/controllers/health.controller';

import { Server } from '@/server';

describe('HealthController', () => {
  let app: Application;

  beforeAll(() => {
    app = new Server(express()).getServer();

    const controller = new HealthController();
    app.get('/health', controller.getHealth);
  });

  it('GET /health should return status 200 and { health: "OK!" } when GET /health', async () => {
    const response = await request(app).get('/health');

    expect(response.status).toEqual(200);
    expect(response.body).toEqual({ health: 'OK!' });
  });
});

Routes Setup (health.router.ts):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express, { Router } from 'express';
import HealthController from '@/controllers/health.controller';
export class HealthRoutes {
private router: Router;
constructor() {
this.router = express.Router();
}
public getRoutes(): Router {
const controller = new HealthController();
this.router.get('/health', controller.getHealth);
return this.router;
}
}
export const healthRoutes = new HealthRoutes();
</code>
<code>import express, { Router } from 'express'; import HealthController from '@/controllers/health.controller'; export class HealthRoutes { private router: Router; constructor() { this.router = express.Router(); } public getRoutes(): Router { const controller = new HealthController(); this.router.get('/health', controller.getHealth); return this.router; } } export const healthRoutes = new HealthRoutes(); </code>
import express, { Router } from 'express';

import HealthController from '@/controllers/health.controller';

export class HealthRoutes {
  private router: Router;

  constructor() {
    this.router = express.Router();
  }

  public getRoutes(): Router {
    const controller = new HealthController();

    this.router.get('/health', controller.getHealth);

    return this.router;
  }
}

export const healthRoutes = new HealthRoutes();

Router index.ts:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { Application } from 'express';
import { serverSchema } from '@/config/environment';
import { healthRoutes } from './health.router';
const applicationRoutes = (app: Application) => {
const routes = () => {
app.use(serverSchema.BASE_URL, healthRoutes.getRoutes());
};
routes();
};
export default applicationRoutes;
</code>
<code>import { Application } from 'express'; import { serverSchema } from '@/config/environment'; import { healthRoutes } from './health.router'; const applicationRoutes = (app: Application) => { const routes = () => { app.use(serverSchema.BASE_URL, healthRoutes.getRoutes()); }; routes(); }; export default applicationRoutes; </code>
import { Application } from 'express';

import { serverSchema } from '@/config/environment';

import { healthRoutes } from './health.router';

const applicationRoutes = (app: Application) => {
  const routes = () => {
    app.use(serverSchema.BASE_URL, healthRoutes.getRoutes());
  };

  routes();
};

export default applicationRoutes;

When I run the tests I get the following error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>stderr | src/config/environment.ts:65:11
[
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: [ 'HOST' ],
message: 'Required'
},
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: [ 'DATABASE_URL' ],
message: 'Required'
},
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: [ 'GITHUB_SECRET' ],
message: 'Required'
}
]
</code>
<code>stderr | src/config/environment.ts:65:11 [ { code: 'invalid_type', expected: 'string', received: 'undefined', path: [ 'HOST' ], message: 'Required' }, { code: 'invalid_type', expected: 'string', received: 'undefined', path: [ 'DATABASE_URL' ], message: 'Required' }, { code: 'invalid_type', expected: 'string', received: 'undefined', path: [ 'GITHUB_SECRET' ], message: 'Required' } ] </code>
stderr | src/config/environment.ts:65:11
[
  {
    code: 'invalid_type',
    expected: 'string',
    received: 'undefined',
    path: [ 'HOST' ],
    message: 'Required'
  },
  {
    code: 'invalid_type',
    expected: 'string',
    received: 'undefined',
    path: [ 'DATABASE_URL' ],
    message: 'Required'
  },
  {
    code: 'invalid_type',
    expected: 'string',
    received: 'undefined',
    path: [ 'GITHUB_SECRET' ],
    message: 'Required'
  }
]

It appears that some environment variables are missing or not defined properly. How can I ensure all required environment variables are correctly loaded during testing and application runtime?

All the environment variables are set in my .env.development.local file.
The zod schema correctly defines and validates the variables.

How can I ensure that my Node.js application correctly loads and validates all required environment variables during tests and runtime?

What am I missing or doing incorrectly?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật