使用Passport js进行身份验证的端点测试

时间:2020-04-21 16:11:27

标签: node.js integration-testing passport.js chai passport-local

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

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

基本上我的测试想要:

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

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

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

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

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

1 个答案:

答案 0 :(得分: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@email.com', 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?-可以节省很多时间。

我希望添加其他帖子可以帮助其他人。