'request.cookies is undefined when using Supertest
I'm passing my authentication token via an HTTP-Only cookie in my NestJS API.
As such, when writing some E2E tests for my Auth endpoints, I'm having an issue with cookies not being where I expect them.
Here's my pared-down test code:
describe('auth/logout', () => {
it('should log out a user', async (done) => {
// ... code to create user account
const loginResponse: Response = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: newUser.email, password });
// get cookie manually from response.headers['set-cookie']
const cookie = getCookieFromHeaders(loginResponse);
// Log out the new user
const logoutResponse: Response = await request(app.getHttpServer())
.get('/auth/logout')
.set('Cookie', [cookie]);
});
});
In my JWT Strategy, I'm using a custom cookie parser. The problem I'm having is that request.cookies is always undefined when it gets to the parser. However, the cookie will be present in request.headers.
I'm following the manual cookie example from this Medium article: https://medium.com/@juha.a.hytonen/testing-authenticated-requests-with-supertest-325ccf47c2bb, and there don't appear to be any other methods available on the request object to set cookies.
If I test the same functionality from Postman, everything works as expected. What am I doing wrong?
Solution 1:[1]
I know this is an old thread but...
I also had req.cookies undefined, but for a different reason.
I'm testing my router independently, not the top level app. So I bootstrap the app in beforeEach and add the route to test.
I was getting req.cookies undefined because express 4 requires the cookieParser middleware to be present to parse the cookies from the headers.
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const request = require('supertest');
const {router} = require('./index');
describe('router', () => {
let app;
beforeAll(() => {
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/', router);
});
beforeEach(() => jest.clearAllMocks());
it('GET to /', async () => {
const jwt = 'qwerty-1234567890';
const resp = await request(app)
.get('/')
.set('Cookie', `jwt=${jwt};`)
.set('Content-Type', 'application/json')
.send({});
});
});
Testing this way allows me to unit test a router in isolation of the app. The req.cookies turn up as expected.
Solution 2:[2]
As per the article you're following, the code at https://medium.com/@juha.a.hytonen/testing-authenticated-requests-with-supertest-325ccf47c2bb :
1) has the 'cookie' value in .set('cookie', cookie) in lowercase and in your code it's in Pascal case ==> Have you tried with lowercase in your code instead ?
2) the cookie value assigned to the 'cookie' header is not an array, whereas in your code you're assigning an array ==> Have you tried with a non array value ?
So to resume, can you try with the following code:
describe('auth/logout', () => {
it('should log out a user', async (done) => {
// ... code to create user account
const loginResponse: Response = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: newUser.email, password });
// get cookie manually from response.headers['set-cookie']
const cookie = getCookieFromHeaders(loginResponse);
// Log out the new user
const logoutResponse: Response = await request(app.getHttpServer())
.get('/auth/logout')
.set('cookie', cookie) // <== here goes the diff
.expect(200, done);
});
});
Let us know if that helps :)
Solution 3:[3]
Late but I hope I can help you. The problem is in the initialization of the app object. Probably in your main.ts file you have some middlewares configured as they are: cors and queryParse. You must also put them in your tests when you create the app.
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
const app = moduleFixture.createNestApplication();
// Add cors
app.enableCors({
credentials: true,
origin: ['http://localhost:4200'],
});
// Add cookie parser
app.use(cookieParser());
await app.init();
Solution 4:[4]
The t1.SubEnd is Null causes it to pick the same top 1 everytime - if you set it to equal itself, then it reevaluates it.
UPDATE TableA
SET MobPhoneID= t2.MobPhoneID
FROM TableA t1
CROSS APPLY (
SELECT TOP 1 MobPhoneID
FROM TableB
WHERE t1.SubEnd = t1.SubEnd
ORDER BY newid()
) t2
I've previously used this method and got the expected results.
Solution 5:[5]
If a mobile phone can be assigned only once?
Then assigning by random row_number could do it.
;with A as ( select *, row_number() over (order by SubStart) rn from TableA where subend is null ) , B as ( select *, row_number() over (order by newid()) rn from TableB ) update A set MobPhoneID = B.MobPhoneID from B where B.rn = A.rn
select a.*, b.Manufacturer from TableA a left join TableB b on b.MobPhoneID = a.MobPhoneID order by SubscriptionIDSubscriptionID | Number | SubStart | SubEnd | MobPhoneID | Manufacturer -------------: | -----: | :------- | :------ | ---------: | :----------- 1 | 321 | 2013-01 | null | 3 | Apple 2 | 123 | 2013-02 | 2014-02 | null | null 3 | 321 | 2013-03 | null | 1 | Samsung 4 | 444 | 2013-04 | 2013-04 | null | null 5 | 555 | 2013-05 | null | 2 | LG
Demo on db<>fiddle here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GetafixIT |
| Solution 2 | A. Maitre |
| Solution 3 | Robe |
| Solution 4 | SeanR |
| Solution 5 |
