'Setting Bearer Token in the header section while testing with Supertest

I'm trying to add the Bearer in the header section in POST request while testing with Supertest. I tried many methods. I'm a beginner in testing. Please suggest some better ways to achieve this.

here is my sample code. What is wrong with this?

it('POST/userAuth', async (done) => {
  const res = await request
                          .post('/v1/user/haha')
                          .set('Authorization', `bearer ${Token}`)
                          .send({
                            title: 'Some random text',
                            options: [
                              { start: hello, end: world },
                              { start: good, end: bye },
                            ],
                          });


Solution 1:[1]

You can set a request header like this:

const request = require('supertest');
const express = require('express');

const app = express();

const TOKEN = 'some_token';

describe('POST /some-url', function() {
  it('does something', function(done) {
    request(app)
      .post('/some-url')
      .send({ body: 'some-body' })
      .set('Authorization', `Bearer ${TOKEN}`)
      .expect(200, done);
  });
});

Solution 2:[2]

in superagent docs you can find specialized .auth method

interface Request extends Promise<Response> {
    auth(user: string, pass: string, options?: { type: "basic" | "auto" }): this;
    auth(token: string, options: { type: "bearer" }): this;
    ...
}

(supertest is using superagent under the hood)

I prefer to set auth in before function for all tests in the set.

import * as Koa from 'koa';
import * as http from 'http';
import { agent as superagent } from 'supertest';
import { UserController } from './user-controller';

const testBearerToken = 'test-bearer-token';

describe('user controller', async () => {

    context('simple user', async () => {
        it('should save user', async () => {
            const response = await test
                .post('/v1/user/haha')
                // you can here, but rather set it in the before function
                //.auth(testBearerToken, { type: 'bearer' });
                .send({
                    title: 'Some random text',
                    options: [
                        { start: 'hello', end: 'world' },
                        { start: 'good', end: 'bye' },
                    ],
                });
            // .expect(...)

            // expect(response)...
        });
    });

    let test;
    before(async () => {
        const app = new Koa();
        const userController = new UserController();
        app.use(userController.middleware());
        test = superagent(http.createServer(app.callback()))
            .auth(testBearerToken, { type: 'bearer' });
    });

});

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 oozywaters
Solution 2