I've been trying to use internetross's March 2018 answer to no avail. I too am using Jest, Supertest, and in my case Koa and Passport.
Using REST client in Visual Studio, no problem. The session gets pass through, Passport authenticates, and I get data. But in Jest, no go. I can login fine, I get Koa:sess fine, but I can't make an authenticated request.
Anybody see anything with the below?
const supertest = require('supertest')
const app = require('../app.js')
const http = require('http')
const agent = supertest.agent((http.createServer(app.callback())))
let session = null
beforeAll(async () => {
const response = await agent
.post('/v1/users/login')
.set({'content-Type': 'application/json'})
.send({ username: 'username', password: 'password' })
session = response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.join('; ')
console.log(stringify(session))
expect(response.status).toEqual(200)
})
describe('user tests', () => {
test('data', async () => {
const response = await agent.get('/v1/users/data?dataIdId=140934')
.set('Cookie', session)
expect(response.status).toEqual(200)
})
})
Of course another question is why this is even necessary if you are using agent. But I've made no progress on that either.
Thanks in advance.
After lots of sleuthing, I finally found the answer. Courtesy of https://github.com/facebook/jest/issues/3547#issuecomment-397183207.
I had to replace
session = response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.join('; ')
with
response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.forEach(c => agent.jar.setCookie(c));
Big sigh.