Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 },
                            ],
                          });
like image 506
aravind ks Avatar asked Nov 20 '25 00:11

aravind ks


1 Answers

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);
  });
});
like image 135
oozywaters Avatar answered Nov 21 '25 13:11

oozywaters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!