使用Passport js的经过身份验证的端点测试

问题描述 投票:0回答:1

我正在尝试在我的应用中测试经过身份验证的终结点。我的节点应用程序使用快速,快速会话,本地护照,React和下一步进行身份验证。

我花了太多时间试图解决这个问题,找不到解决方案。

基本上我的测试希望:

  • 发送登录请求并登录
  • 将请求发送到经过验证的路由
  • 收到适当的回复

我的问题是,登录请求和经过身份验证的路由请求之间没有持久性。

当我发送登录请求时,护照会序列化用户,并将req.user和req._passport.session设置为适当的值。

在下一个请求-经过身份验证的路由上,我的中间件寻找req.passport._session或req.user,但都不存在。我会收到401未经授权的回复。

我在下面发布了我的解决方案,导致我花了很长时间才弄清楚。

node.js integration-testing passport.js chai passport-local
1个回答
0
投票

我用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?-本可以节省很多时间。

我希望添加其他帖子将对此有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.