使用Supertest时未定义request.cookies

使用Supertest时未定义request.cookies,cookies,nestjs,supertest,Cookies,Nestjs,Supertest,我正在通过NestJSAPI中的仅HTTP cookie传递身份验证令牌 因此,在为我的Auth端点编写一些E2E测试时,我遇到了一个问题,即cookie并没有达到预期的效果 以下是我的精简测试代码: 在我的JWT策略中,我使用一个定制的cookie解析器。我遇到的问题是,request.cookies在到达解析器时总是undefined。但是,cookie将出现在request.headers中 我遵循的是本文中的手动cookie示例:,并且在请求对象上似乎没有任何其他方法可用于设置cook

我正在通过NestJSAPI中的仅HTTP cookie传递身份验证令牌

因此,在为我的Auth端点编写一些E2E测试时,我遇到了一个问题,即cookie并没有达到预期的效果

以下是我的精简测试代码:

在我的JWT策略中,我使用一个定制的cookie解析器。我遇到的问题是,
request.cookies
在到达解析器时总是
undefined
。但是,cookie将出现在
request.headers

我遵循的是本文中的手动cookie示例:,并且在请求对象上似乎没有任何其他方法可用于设置cookie


如果我从Postman测试相同的功能,一切都会正常工作。我做错了什么?

根据您下面的文章,代码位于:
1)
.set('cookie',cookie)
中的'cookie'值是小写的,而在您的代码中它是Pascal大小写==>您在代码中尝试过小写吗?
2) 分配给“cookie”头的cookie值不是数组,而在代码中分配的是数组==>是否尝试使用非数组值?

因此,要继续,请尝试以下代码:

description('auth/logout',()=>{
它('应该注销用户',异步(完成)=>{
//…创建用户帐户的代码
const loginResponse:Response=等待请求(app.getHttpServer())
.post('/auth/login')
.send({用户名:newUser.email,密码});
//从response.headers['set-cookie']手动获取cookie
const cookie=getCookieFromHeaders(loginResponse);
//注销新用户
const logoutResponse:Response=等待请求(app.getHttpServer())
.get('/auth/logout')

.set('cookie',cookie)/我知道这是一个旧线程,但是

我也有未定义的req.cookies,但原因不同

我正在独立测试我的路由器,而不是顶级应用程序。因此,我会在每次测试之前引导应用程序,并将路由添加到测试中

我得到了未定义的req.cookies,因为Express4需要cookieParser中间件来解析来自标头的cookies

例如


const express=require('express');
const bodyParser=require('body-parser');
const cookieParser=require('cookie-parser');
const request=require('supertest');
const{router}=require('./索引');
描述('路由器',()=>{
让应用程序;
以前(()=>{
app=express();
use(bodyParser.json());
use(bodyParser.urlencoded({extended:true}));
使用(cookieParser());
应用程序使用(“/”,路由器);
});
之前(()=>jest.clearAllMocks());
它('GET to/',async()=>{
常数jwt='qwerty-1234567890';
const resp=等待请求(应用程序)
.get(“/”)
.set('Cookie','jwt=${jwt};`)
.set('Content-Type','application/json')
.send({});
});
});

通过这种方式进行测试,我可以在应用程序隔离的情况下对路由器进行单元测试。req.cookies如预期的那样出现。

您好。我为响应太晚表示歉意。是的,我以前尝试过将值小写并使用非数组值,但cookie仍然作为标头,而不是在
请求中。cookies
集合中围绕这一点,我添加了一个提取器,以从标题中提取令牌,作为我的Passport策略的后备。您是否使用Fastify?如果是这样,您在创建测试应用程序时仍然需要注册FastifyCookies。不,我没有起诉Fastify。很抱歉,回复太慢,我生病了一段时间。非常感谢您的帖子,我必须注册我试试看。
describe('auth/logout', () => {
  it('should log out a user', async (done) => {
    // ... code to create user account

    const loginResponse: Response = await request(app.getHttpServer())
                                              .post('/auth/login')
                                              .send({ username: newUser.email, password });

    // get cookie manually from response.headers['set-cookie']
    const cookie = getCookieFromHeaders(loginResponse);

    // Log out the new user
    const logoutResponse: Response = await request(app.getHttpServer())
                                            .get('/auth/logout')
                                            .set('Cookie', [cookie]);

  });
});