1

I'm trying to test an authenticated endpoint in my app. My node app uses express, express session, passport-local, react and next for auth.

I've spent way too many hours trying to solve this problem and could not find a solution.

Basically my test would like to:

  • send a login request and login
  • send a request to an authenticated route
  • receive the appropriate response

My issue was that I had no persistence between the login request and the authenticated route request.

When I sent the login request, passport serializes the user and sets req.user and req._passport.session to the appropriate values.

On the next request - the authenticated route, my middleware looks for req.passport._session or req.user but neither exist. I would get the 401 unauthorized response.

I posted my solution below that took me way too long to figure out.

1 Answers1

0

I solved the persistence issue with Chai HTTP - which uses superagent.

The solution was pretty simple once I had the correct tools. I used the tutorial from the chai-http page but changed it to use async await and try 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);
   } 
  }); 
});

I now see this post How to authenticate Supertest requests with Passport? - which would have saved me a lot of time.

I hope adding having another post will help someone else with this.