我在使用 Express 的“cookieSession”使用 Supertest 测试 Express 应用程序时遇到问题。当我session从 Express使用时,一切正常,但cookieSession不能正确使用 PassportJS。
我正在使用 PassportJS 对用户进行身份验证并将用户设置为请求对象 (req.user)。所以/login按预期工作,它返回正确的set-cookie标头,但在下一个请求中,身份验证失败req.user,即使它正确反序列化/序列化用户,也不会使用用户对象设置属性
版本:
这就是我初始化超级代理的方式:
import * as supertest from 'supertest';
import * as superagent from 'superagent';
import app from '../../app';
const request = supertest.agent(app);
Run Code Online (Sandbox Code Playgroud)
我在测试之前运行登录(使用异步/等待功能):
await request.post('/login').send({
email: 'some@email.com',
password: 'plainpassword'
});
Run Code Online (Sandbox Code Playgroud)
然后我向后端发出第一个请求以检索数据:
const readResponse: superagent.Response = await
request.post('/getData').send(requestBody);
Run Code Online (Sandbox Code Playgroud)
这就是它失败的地方。它返回状态代码 401,因为 PassportJS 不提供用户数据来请求对象。也许它不在 req.user 中?
在 app.ts 中,我像这样设置了 cookieSession 和passportJS 会话:
app.use(cookieSession({
keys: [process.env.SESSION_SECRET], …Run Code Online (Sandbox Code Playgroud)