admin管理员组文章数量:1312817
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
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
- Please provide enough code so others can better understand or reproduce the problem. – Community Bot Commented Mar 2, 2022 at 2:36
- Just a quick guess. You might not have cookie parser active / added to your test environment. – phlebotinum Commented Aug 4, 2022 at 15:30
2 Answers
Reset to default 9New 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({});
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
本文标签: javascriptI am trying to set a cookie in supertest but it does not workStack Overflow
版权声明:本文标题:javascript - I am trying to set a cookie in supertest but it does not work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741883909a2402908.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论