#NestJS Testing Validation Error with Zod

3 messages · Page 1 of 1 (latest)

errant ruin
#

Hi, I have a problem with my application tests after applying Zod.
I have a simple test, this one:

import { Test, TestingModule } from '@nestjs/testing';
import { MailerProcessor } from '../processors/mailer.processor';

describe('MailerService', () => {
  let service: MailerProcessor;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [MailerProcessor],
    }).compile();

    service = module.get<MailerProcessor>(MailerProcessor);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

And my validation scheme is this (also simple):

import 'dotenv/config';
import { z } from 'zod';

interface EnvVars {
  PORT: number;
  TIMEOUT_REQUEST: number;
  NODE_ENV: string;
}

const MIN_PORT_NUMBER: number = 3000;
const MAX_PORT_NUMBER: number = 65536;
const DEFAULT_TIMEOUT_REQUEST: number = 5000;

const envsSchema = z.object({
  PORT: z.coerce
    .number()
    .positive()
    .max(MAX_PORT_NUMBER, `Port should be >= 0 and < 65536`)
    .default(MIN_PORT_NUMBER),

  TIMEOUT_REQUEST: z.coerce
    .number()
    .positive()
    .default(DEFAULT_TIMEOUT_REQUEST),

  NODE_ENV: z.string().default('development'),
});

const envVars = envsSchema.parse({ ...process.env }) as EnvVars;

export const Envs = {
  ENVIRONMENT: {
    PORT: Number(envVars.PORT),
    TIMEOUT_REQUEST: envVars.TIMEOUT_REQUEST,
    NODE_ENV: envVars.NODE_ENV,
  },
};
#

However, when I run the tests I get the following error:

 FAIL  src/mailer/test/mailer.service.spec.ts
  ● Test suite failed to run

    ZodError: [
      {
        "code": "invalid_type",
        "expected": "number",
        "received": "nan",
        "path": [
          "PORT"
        ],
        "message": "Expected number, received nan"
      },
    ]

      65 | });
      66 |
    > 67 | const envVars = envsSchema.parse({          ^
      68 |   ...process.env,
      70 | }) as EnvVars;

      at Object.get error [as error] (../node_modules/zod/lib/types.js:43:31)
      at ZodObject.parse (../node_modules/zod/lib/types.js:143:22)
      at Object.<anonymous> (common/config/env/envs.ts:67:28)
      at Object.<anonymous> (mailer/use-cases/send-verification-email-processor.use-case.ts:7:1)   
      at Object.<anonymous> (mailer/use-cases/index.ts:1:1)
      at Object.<anonymous> (mailer/processors/mailer.processor.ts:7:1)
      at Object.<anonymous> (mailer/test/mailer.service.spec.ts:2:1)

Test Suites: 1 failed, 1 total                                                                     
Tests:       0 total                                                                               
Snapshots:   0 total
Time:        3.289 s, estimated 5 s
Ran all test suites.
sudden void
#

The environment variable PORT is likely undefined when the tests run. Try logging it before calling the parse