You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为NestJS+Fastify的E2E测试注册Cookie中间件?

解决NestJS Fastify E2E测试中response.setCookie报错问题

报错response.setCookie is not a function的原因是Fastify默认不支持Express风格的Cookie操作方法,需要安装并注册Fastify官方的Cookie插件。

解决步骤:

  1. 安装依赖
    执行以下命令安装Fastify Cookie插件:
npm install @fastify/cookie
# 或使用yarn
yarn add @fastify/cookie
  1. 在测试模块中注册插件
    修改你的app.e2e-spec.ts代码,在app.init()之前添加插件注册逻辑:
let app: NestFastifyApplication

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

  app = moduleRef.createNestApplication<NestFastifyApplication>(
    new FastifyAdapter(),
  )

  app.useGlobalPipes(new ValidationPipe())
  // 注册Fastify Cookie插件
  await app.register(require('@fastify/cookie'))

  await app.init()
  await app.getHttpAdapter().getInstance().ready()

  await app.listen(3333)
})

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

补充说明:

注册插件后,Fastify响应对象会提供符合NestJS要求的Cookie操作方法,此时接口中调用response.setCookie就能正常工作。如果你的生产环境代码也使用Fastify,同样需要在main.ts中注册该插件,保证测试与生产环境行为一致。

内容的提问来源于stack exchange,提问作者Luka Fridonich Donadze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:00:16