我正在尝试在我的应用中测试经过身份验证的终结点。我的节点应用程序使用快速,快速会话,本地护照,React和下一步进行身份验证。
我花了太多时间试图解决这个问题,找不到解决方案。
基本上我的测试希望:
我的问题是,登录请求和经过身份验证的路由请求之间没有持久性。
当我发送登录请求时,护照会序列化用户,并将req.user和req._passport.session设置为适当的值。
在下一个请求-经过身份验证的路由上,我的中间件寻找req.passport._session或req.user,但都不存在。我会收到401未经授权的回复。
我在下面发布了我的解决方案,导致我花了很长时间才弄清楚。
我用Chai HTTP解决了持久性问题-使用superagent。
一旦有了正确的工具,解决方案就非常简单。我使用了chai-http页面中的教程,但将其更改为使用async await并尝试catch。
const { assert } = require('chai');
const chai = require('chai');
const { expect } = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
describe('/authenticatedRequest', () => {
it('should respond appropriately', async () => {
const agent = chai.request.agent('http://localhost:8000');
try {
await agent
.post('/rootPath/loginLocal')
.send({ email: '[email protected]', password: 'password' });
const authenticatedResponse = await agent.get('/rootPAth/authenticatedRoute');
assert.deepEqual(successResponse, workoutRes);
} catch (e) {
console.log(e);
}
});
});
我现在看到这篇文章How to authenticate Supertest requests with Passport?-本可以节省很多时间。
我希望添加其他帖子将对此有所帮助。