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

NestJS中Passport.js HttpOnly Cookie认证在supertest测试中失效问题

问题根因

测试场景下req.cookies为空的核心原因通常是两个:

  1. 测试初始化的Nest应用实例未注册cookie-parser中间件,无法把请求头中的Cookie字符串解析为req.cookies对象
  2. Cookie签名配置不匹配,导致解析后的cookie没有挂载到req.cookies下

可行解决方案

步骤1:测试环境补全cookie-parser注册

你在main.ts中注册的中间件不会自动应用到测试创建的Nest实例,需要在测试初始化时手动添加,保持和生产环境配置完全一致:

import * as cookieParser from 'cookie-parser';
import { Test } from '@nestjs/testing';
import { AppModule } from './app.module';
import { jwtConstants } from './auth/constants';

// 测试初始化app的逻辑
let app: INestApplication;
beforeAll(async () => {
  const moduleFixture = await Test.createTestingModule({
    imports: [AppModule],
  }).compile();
  app = moduleFixture.createNestApplication();
  // 和main.ts配置完全一致,开启了签名就传对应秘钥,没开就不传
  app.use(cookieParser(jwtConstants.secret));
  await app.init();
});

步骤2:确认Cookie签名配置匹配

如果你在登录接口设置Cookie时开启了signed: true配置:

// AuthController登录接口的Cookie设置逻辑
response.cookie('auth-cookie', { access_token: jwtToken }, {
  httpOnly: true,
  signed: true, // 开启了签名
  path: '/'
})

那需要把JwtStrategy中的取值逻辑改成从signedCookies获取:

let data = request?.signedCookies?.['auth-cookie'];

步骤3:使用supertest agent简化Cookie传递(可选,更稳妥)

不需要手动提取、传递Cookie,agent会自动维护请求上下文的Cookie,避免格式错误:

it('gives the current user when the token is valid', async () => {
  // 初始化agent,自动管理Cookie
  const agent = request.agent(app.getHttpServer());
  
  // 先登录,agent自动保存返回的Cookie
  await agent.post('/auth/login').send({
    username: 'joe.doe@gmail.com',
    password: 'password'
  });

  // 直接发起请求,自动携带Cookie
  const { body: user } = await agent.get('/users/me');

  expect(user.email).toEqual('joe.doe@gmail.com');
  expect(user.fullname).toEqual('Joe Doe');
  expect(user.uuid).toBeTruthy();
  expect(user.password).toBeFalsy();
});

内容的提问来源于stack exchange,提问作者mfrachet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:06:04