CodePark/ questions / Testing NestJS apps
START PRACTICINGPRACTICE
Backend question · Backend testing › Testing NestJS apps

Your Nest e2e tests pass, but in production invalid bodies are rejected with 400 that the tests never saw, and every route has an /api prefix the tests don't use. What differs, and how do you prevent the drift?

The e2e app is built from AppModule only. Anything main.ts sets on the app instance is not part of that module, so the test app runs without it.

Things that live in main.ts and get lost:

  • app.useGlobalPipes(new ValidationPipe({ whitelist: true }))
  • setGlobalPrefix('api')
  • enableVersioning()
  • global filters and interceptors
  • middleware such as cookieParser()

So the tests call different routes and skip validation.

Two ways to fix the drift:

  • Put the setup in one configureApp(app) function. Call it from main.ts and from the e2e beforeAll, before app.init().
  • Or register global pieces as providers inside a module, with APP_PIPE, APP_FILTER, APP_INTERCEPTOR and APP_GUARD. Then they come along whenever AppModule is compiled.

Finally, add an e2e test that sends an invalid body and expects 400. If the pipe goes missing again, the build fails.

  • Setup that main.ts does on the app instance is not part of AppModule.
  • Pipes, prefix, versioning, filters and middleware must be applied in the test too.
  • Share one configureApp function between main.ts and the tests.
  • Or register globals with APP_PIPE, APP_FILTER, APP_INTERCEPTOR and APP_GUARD.