eskil4152
eskil4152

Reputation: 147

How to send a signedCookie in Jest test

I am writing tests for my Node.js/express application, and I need to make requests to different APIs. The router requests takes in a signed cookie for some of the endpoints to authenticate the user trying to access said endpoint.

The problem is I am unable to find out how I mock a cookie with authentication details using Jest tests.

Upvotes: 0

Views: 539

Answers (1)

Fadhili Njagi
Fadhili Njagi

Reputation: 158

The cookie-parser library uses the cookie-signature library under the hood. I'm assuming you have access to the encryption key or cookie secret (in .env or wherever). Without it, you can't sign your cookies.

I'm using supertest for requests.

import request from 'supertest';
import { unsign } from 'cookie-signature';
// If your key comes from .env
import dotenv from 'dotenv';
dotenv.config();

const baseURL = 'http://localhost:3000';
const key = process.env.COOKIE_SECRET; // Set your key here. Mine comes from .env

describe('My super awesome test group', () => {
  it('test some stuff', async () => {
    const res = await request(app)
        .get('/your-endpoint')
        .set('Cookie', `myCookie=s:${sign('my value', key)}`);
    expect(res.status).toBe(200);
    // Do other assertions
  });
});

Hope that helps : )

Upvotes: 1

Related Questions