4
votes

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.

1
Are the smart single quotes intentional? Perhaps you should edit them to be straight single quotes so they aren't distracting to readers. e.g.: ‘supertest’ should be 'supertest' and all other occurrences.Wyck
Nope. B products of me writing the text in a Bear on a Mac before pasting. I'll fix them.Crivens
How do you handle a session in a middleware? Is it stored locally or in memory? Supertest might reboot a app instance in a background after passed test, so if you keep sessions in memory you will lose it.l2ysho
That's a good idea to investigate. I'll look into it more tomorrow. I'm using passport-local. Here's the very simple code setting it up: passport.use( new LocalStrategy(options, (username, password, done) => { User.findOne({ username: username }) .then(user => { if (!user) return done(null, false) if (password === user.password) { return done(null, user) } else { return done(null, false) } }) .catch(err => { return done(err) }) }) )Crivens

1 Answers

1
votes

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.