Despite my best attempts to correctly write test code to authenticate a request agent in Setup blocks or previous describe/it blocks, any request I make from the agent in subsequent describe/it blocks never completes as 200.
Example code:
const request = require('supertest');
const server = require('../server');
let agent = request.agent(server);
let fakePerson = null;
beforeEach(async (done) => {
fakePerson = await Person.createMock();
agent.post(‘/login’)
.send({
email: ‘[email protected]’,
password: ‘password’
})
.end(function(err, res) {
if (err) throw err;
done();
});
});
describe('GET /users/:id', () => {
it ('renders user profile', () => {
return agent
.get(`/users/${fakePerson.id}`)
.expect(200)
});
});
I thought it might have something to do with how I was forming the async calls syntactically. But after trying different ways of returning the login call in the beforeEach
block using return
, .end()
syntax, even async/await, I've determined (ie given up) that the code must be composed properly. Could it be something else?
Referenced articles/resources:
- How to authenticate Supertest requests with Passport?
- https://medium.com/@juha.a.hytonen/testing-authenticated-requests-with-supertest-325ccf47c2bb
- https://gist.github.com/joaoneto/5152248
- https://medium.com/@bill_broughton/testing-with-authenticated-routes-in-express-6fa9c4c335ca
- https://github.com/visionmedia/supertest/issues/46
Package versions:
- "koa": "^2.4.1"
- "koa-passport": "^4.0.1"
- "passport-json": "^1.2.0"
- "passport-local": "^1.0.0"
- "supertest": "^3.0.0"
- "jest": "^22.1.3"