0
votes

I am looking to use supertest to test API requests and responses. Following is what I have tried so far.

route.test.js

const testUtils = require('./setupTestUtils');
let authenticateUser = request.agent(app);
before(function(done){ 
testUtils.login(authenticateUser, userCredentials).then((res) => {
   expect(res.statusCode).to.equal(200);
   done();
}, (err) => {
   console.log(err);
   done(err);
});
});

setupTestUtils.js

function login (rest, testUserLogin) {
let defer = Q.defer();
rest.post('/login')
    .send(testUserLogin)
    .expect(200)
    .end(function () {
        rest.get('/loggedin')
            .expect((res) => {
                if (err) {
                    console.log('ERROR: ' + JSON.stringify(err));
                    defer.reject(err);
                } else {
                    defer.resolve(res);
                }
            })
            .end();
        });
return defer.promise;

}

In my app.js, I use passport to authenticate. After authentication, I use the session.regenerate function to regenerate the session ID to avoid session fixation.

The initial post request to login passes without any failure. However, the subsequent GET request 'loggedIn' fails. This function internally uses the req.isAuthenticated() function from passport. This always returns false.

On investigation, I found that the session ID between the regenerated session and the request object (for req.isAuthenticated()) is different.

From my search, I understand that the cookies should be maintained automatically by the use of 'agent' from supertest. However that doesnt seem to be the case for me. I have also tried maintaining the cookies from the initial response. That doesnt seem to work for me either. " res.headers['set-cookie'] " comes in as undefined (not sure why that is happening either).

Can someone please help me understand what I am missing here.?

Am using versions - Supertest @v6.0.1 and passport @v0.4.1

1

1 Answers

0
votes

I found the solution to my issue in an old github issue raised on supertest's page. Linking it here for reference.

Essentially, the supertest runs express in insecure port and I had configured my session otherwise. Ideally, we would have to check the environment before setting this variable to false - as represented here.

Hope this saves someone the time I spent!