jest: A problem testing Express with Supertest
We are porting our tests from Mocha to Jest and encountered this weird problem.
Do you want to request a feature or report a bug? bug
What is the current behavior?
The following spec tests login and fetching data for an authorized user in Express.js server using Supertest. Before each test suite, it initializes an agent that does the login. In Mocha the test runs without problems. In Jest, however, it successfully logs the user in beforeEach
part, but the subsequent requests don’t use the same credentials, hence, get rejected as unauthorized.
const request = require('supertest');
const api = require('../../src/routes/main');
describe('Concepts API', () => {
let agent;
beforeEach((done) => {
agent = request.agent(api);
agent
.post('/a/login')
.send({
username: 'testerName',
password: 'testerPassword',
})
.expect(200, done);
});
describe('GET concepts/names', () => {
it('returns the list of names of the fist 100 concepts', (done) => {
agent
.get('/concepts/names')
.set('X-Requested-With', 'XMLHttpRequest')
.expect(200)
.end((e, r) => {
expect(r.body.concepts).toBeDefined();
done();
});
});
});
});
What is the expected behavior? Test should pass.
Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system. Jest 20.0.0 Supertest 3.0.0 Express.js 4.15.2
The command used to run Jest (there are no other configs):
jest concepts.spec.js --env=node --runInBand
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 1
- Comments: 15
@jakeorr We seem to use the same middlewares. In case you need a temporary workaround, we went with manually parsing cookies after login and then supplying them in following requests. That is:
Hi, I’m having the same issue. Here’s a simple repro:
I’m doing two requests to test for the same cookie-session being used for both. I expect to see ‘set-cookie’ headers in the first response, and not in the second. Also, the log of req.session for the second request should contain session data from the first. It doesn’t work in Jest. Here’s the output:
When I run this spec with mocha, it works as expected:
A bit of further debugging shows that Jest and Mocha set cookies differently. After login, we return cookies with session info in
Set-Cookie
header. Jest sets all values as a single string,Whereas in Mocha we have two strings:
The subsequent requests use different “Cookie” header in Jest and Mocha. Jest has just the first key-value pair:
Mocha has both:
@thymikee I don’t see an easy way to share our stack, but I believe the culprit is in this cookie setting procedure.
If your cookie has Expires as a date, here is a workaround (@keepitsimple):
Mysteriously, this workaround worked for me locally but not on travis-ci (despite identical node versions). I had to modify it as follows for consistent behaviour across both environments: