Papooch / nestjs-cls

A continuation-local storage (async context) module compatible with NestJS's dependency injection.
https://papooch.github.io/nestjs-cls/
MIT License
390 stars 23 forks source link

can not access to CLS in e2e test after the first sub-test #60

Closed ianzone closed 1 year ago

ianzone commented 1 year ago

Log

Error: Cannot set the key "logTrace". No CLS context available, please make sure that a ClsMiddleware/Guard/Interceptor has set up the context, or wrap any calls that depend on CLS with "ClsService#run"
    at ClsService.set (/home/ian/templates/vite-nest/node_modules/.pnpm/nestjs-cls@3.2.1_77foi4w27ghy47yutmnzv7krjy/node_modules/nestjs-cls/dist/src/lib/cls.service.js:41:19)
    at MiddlewareHost.use (/src/middlewares/authentication/authentication.middleware.ts:26:18)
    at MiddlewareHost.use (/home/ian/templates/vite-nest/node_modules/.pnpm/@nestjs+core@9.3.9_jrq2rdgfp2sx67wmylmrqliwxe/node_modules/@nestjs/core/middleware/utils.js:48:30)
    at /home/ian/templates/vite-nest/node_modules/.pnpm/@nestjs+core@9.3.9_jrq2rdgfp2sx67wmylmrqliwxe/node_modules/@nestjs/core/router/router-proxy.js:9:23
    at Holder.done (/home/ian/templates/vite-nest/node_modules/.pnpm/@fastify+middie@8.1.0/node_modules/@fastify/middie/engine.js:107:13)
    at Object.run (/home/ian/templates/vite-nest/node_modules/.pnpm/@fastify+middie@8.1.0/node_modules/@fastify/middie/engine.js:59:12)

To reproduce:

  1. degit https://github.com/ianzone/vite-nest-fastify to-check
  2. cd to-check
  3. pnpm i
  4. pnpm run test
Papooch commented 1 year ago

I'll have a look. But it might be related to this one: https://github.com/Papooch/nestjs-cls/issues/49

Papooch commented 1 year ago

Okay, so after looking into it, I found the error. In your tests, you never bound the ClsMiddleware - it is only bound in your main.ts, which is not used in the test.

I see you're binding the AuthenticationMiddleware in your AppModule, so I removed the ClsMiddleware registration out from main and added it to your AppModule before the AuthenticationMiddleware like so:

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(ClsMiddleware).forRoutes('(.*)');
    consumer.apply(AuthenticationMiddleware).exclude('/').forRoutes('(.*)');
  }
}

Now the test passes as expected.