I am trying to set a cookie in supertest but it does not work
Asked Answered
J

2

7

I am trying to set a cookie session to a post request in supertest but I cannot. This is my test code:

const app = express();

app.set("trust proxy", true);
app.use(json());
app.use(
  cookieSession({
    signed: false,
    secure: process.env.NODE_ENV !== "test",
  })
);
   
    
    it("this is a test", async () => {
      const response = await request(app)
        .post("/api/users/current")
        .set("Cookie", [
        'express:sess=eyJqd3QiOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKcFpDSTZJakV5TXpRaUxDSmxiV0ZwYkNJNkluUmxjM1JBZEdWemRDNWpiMjBpTENKcFlYUWlPakUyTkRZeE5qazVNREI5LjZybE8zODB2RG1PN0J4cFlhRERZSnBScmhrMEc2X3pvN3BBd2MxYU5rMVEifQ=='
          ])
        .send({});
    
      expect(response.get("Set-Cookie")).toBeDefined();
    });

and this test fails because response.get("Set-Cookie") is undefined

Joettajoette answered 1/3, 2022 at 21:29 Comment(2)
Please provide enough code so others can better understand or reproduce the problem.Birk
Just a quick guess. You might not have cookie parser active / added to your test environment.Wellesz
T
9

New versions of cookie-session will require the session to start with the keyword session:

"session=eyJqd3QiOiJ..."

As opposed to express:sess:

"express:sess=eyJqd3QiOiJ..."

Another thing that helped me was the use of the agent. I did that based on the supertest docs.

import express from 'express';
import request from 'supertest';

const app = express();
const agent = request.agent(app); // <-- Important

const response = agent // <-- Request through agent
  .post('/api/users/current')
  .set('Cookie', [
    'session=eyJqd3QiOiJ...', // <-- No 'express:sess' (Cropped for demo)
  ])
  .send({});
Terrorism answered 14/9, 2022 at 17:23 Comment(3)
May we please have the link to the documentation you're referring to?Fachanan
Hello @SudharshannD - Yes of course. I added an image and the link to the supertest docs. I hope it helps.Terrorism
@SudharshannD I added a comment about the agent. That made a difference when I was testing my code.Terrorism
R
-3

According to my investigation, Supertest library is not stable. Majority developers have difficulties to set or retrieve cookies during testing.

You can take a look at this link: how to set signed cookies

Rang answered 25/4, 2022 at 21:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.