1

我正在尝试在我的应用程序中测试经过身份验证的端点。我的节点应用程序使用 express、express session、passport-local、react 和 next 进行身份验证。

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

基本上我的测试想要:

  • 发送登录请求并登录
  • 向经过身份验证的路由发送请求
  • 收到适当的回应

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

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

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

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

4

1 回答 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@email.com', password: 'password' });
     const authenticatedResponse = await agent.get('/rootPAth/authenticatedRoute');
     assert.deepEqual(successResponse, workoutRes);
   } catch (e) {
     console.log(e);
   } 
  }); 
});

我现在看到这篇文章如何使用 Passport 验证 Supertest 请求?- 这会为我节省很多时间。

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

于 2020-04-21T16:11:27.353 回答