Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Headers ('Authorization','Bearer token') in Mocha Test cases

I am writing a test case to test my API . When I try to test for any open API, it is working fine. But When I try to send Authorization Token along with my API, it is not working. Here is the code:

The way i am sending headers is:

.set("Authorization", "Bearer " + token)

Is it the correct way of sending?

I have tried to send the Authorization token in Auth. But not able to get the same. But when I tried to consume same in Postman, it is working fine.

    it("Get some random Info", function(done) {
        chai
          .request(baseUrl)
          .get("/someRandomApi")
          .set("Authorization", "Bearer " + token)
          .end(function(err, res) {
            expect(res).to.have.status(200);
            done();
          });
      });
like image 338
Leela Vathi Avatar asked Nov 02 '25 04:11

Leela Vathi


1 Answers

I like to set up my tests in the following way:

let baseUrl = 'http://localhost:9090'
let token = 'some_authorization_token'

First I would instantiate my variables baseUrl and token at the very top of the test, right after use() part.

Next to come is the setup of the test.

    it("Get some random Info", function(done) {
       chai.request(baseUrl)
         .get('/someRandomApi')
         .set({ "Authorization": `Bearer ${token}` })
         .then((res) => {
            expect(res).to.have.status(200)
            const body = res.body
            // console.log(body) - not really needed, but I include them as a comment
           done();
         }).catch((err) => done(err))
    });

Now, .set() doesn't necessarily have to be like mine, works in your case as well.

like image 146
buck80 Avatar answered Nov 03 '25 17:11

buck80



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!