Validate requests and test routes

12.6.0

Validate inputs at the API boundary. Return a clear HTTP status for invalid input and missing records.

On this page

Use a DTO with a validation pipe

Install class-validator and class-transformer for ValidationPipe. Create DTOs as classes and add validation decorators. With whitelist enabled, properties without validation decorators are removed. Add forbidNonWhitelisted to reject those properties instead.

import { Body, Controller, Post, ValidationPipe } from "@nestjs/common";
import { IsInt, IsNotEmpty, IsString, Min } from "class-validator";

class CreateOrderDto {
  @IsString()
  @IsNotEmpty()
  item!: string;

  @IsInt()
  @Min(1)
  quantity!: number;
}

@Controller("orders")
export class OrdersController {
  @Post()
  create(@Body(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
    input: CreateOrderDto) {
    return input;
  }
}

Check both valid and invalid requests

Test service logic in isolation. Use an end-to-end test for the HTTP route to verify request parsing, validation, status, and response together. Cover a valid body and an invalid body, such as quantity 0.

// In the end-to-end suite with the Nest application started.
import request from "supertest";

it("accepts an order with a positive quantity", async () => {
  const order = { item: "Notebook", quantity: 2 };
  await request(app.getHttpServer()).post("/orders").send(order).expect(201, order);
});

it("rejects an order with quantity zero", async () => {
  await request(app.getHttpServer())
    .post("/orders")
    .send({ item: "Notebook", quantity: 0 })
    .expect(400);
});

Official references