How to register cookie middleware for e2e testing?? - @nestjs/testing and fastify adapter

542 views Asked by At

I use pactum and jest for e2e testing

but while testing the endpoint which sets cookies, nest throws an error

[Nest] 3364  - 01/03/2023, 5:35:15 PM   ERROR [ExceptionsHandler] response.setCookie is not a function
TypeError: response.setCookie is not a function

But how to register cookie middleware for testing module??

app.e2e-spec.ts

      let app: INestApplication
    
      beforeAll(async () => {
        const moduleRef = await Test.createTestingModule({
          imports: [AppModule],
        }).compile()
    
        app = moduleRef.createNestApplication<NestFastifyApplication>(
          new FastifyAdapter(),
        )
    
        app.useGlobalPipes(new ValidationPipe())
    
        await app.init()
        await app.getHttpAdapter().getInstance().ready()
    
        await app.listen(3333)
      })
    
      afterAll(() => {
        app.close()
      })
1

There are 1 answers

4
Jay McDoniel On BEST ANSWER

Just like you register it in your main.ts. You need to call app.register() to register the middleware before you call app.listen()

let app: NestFastifyApplication

beforeAll(async () => {
  const moduleRef = await Test.createTestingModule({
    imports: [AppModule],
  }).compile()

  app = moduleRef.createNestApplication<NestFastifyApplication>(
    new FastifyAdapter(),
  )
  
  app.useGlobalPipes(new ValidationPipe())
  app.register(fastifyCookie, cookieOptions) // register the middleware
  await app.init()
  await app.getHttpAdapter().getInstance().ready()
  
  await app.listen(3333)
})

afterAll(() => {
  app.close()
})