Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing JWT Authentication Using Mocha and Chai

I'm stuck writing a test for my get endpoint which requires a token of the admin to return a list of users.

Here is my user endpoint:

   app.get("/users", (req,res) => {
      const payload = req.payload

      if (payload && payload.user === "admin") {
         User.find({}, (err, users) => {
            if(!err) {
               res.status(200).send(users)
            } else { res.status(500).send(err) }
         })
      } else { res.status(500).send("Authentication Error!)}
   }

Here's my jwt middleware:

   module.exports = {
  validateToken: (req, res, next) => {
    const authorizationHeader = req.headers.authorization;
    let result;
    if (authorizationHeader) {
      const token = req.headers.authorization.split(" ")[1]; // Bearer <token>
      const options = {
        expiresIn: "2d",
        issuer: "clint maruti"
      };
      try {
        // verify makes sure that the token hasn't expired and has been issued by us
        result = jwt.verify(token, process.env.JWT_SECRET, options);
        // Let's pass back the decoded token to the request object
        req.decoded = result;
        // We call next to pass execution to the subsequent middleware
        next();
      } catch (err) {
          // Throw an error just in case anything goes wrong with verification
          throw new Error(err)
      }
    } else {
        result = {
            error: 'Authentication error. Token required.',
            status: 401
        }
        res.status(401).send(result)
    }
  }
};

Here's my sample test:

let User = require("../models/users");

// Require dev dependencies
let chai = require("chai");
let chaiHttp = require("chai-http");
let app = require("../app");
let should = chai.should();

chai.use(chaiHttp);

let defaultUser = {
  name: "admin",
  password: "admin@123"
};

let token;

// parent block
describe("User", () => {
  beforeEach(done => {
    chai
      .request(app)
      .post("/users")
      .send(defaultUser)
      .end((err, res) => {
        res.should.have.status(200);
        done();
      });
  });
  beforeEach(done => {
    chai
      .request(app)
      .post("/login")
      .send(defaultUser)
      .end((err, res) => {
        token = res.body.token;
        res.should.have.status(200);
        done();
      });
  });
  afterEach(done => {
    // After each test we truncate the database
    User.remove({}, err => {
      done();
    });
  });

  describe("/get users", () => {
    it("should fetch all users successfully", done => {
      chai
        .request(app)
        .set("Authentication", token)
        .get("/users")
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a("object");
          res.body.should.have.property("users");
          done();
        });
    });
  });
});

Problem: My test is giving me an assertion error 500 instead of 200 of the status code, I have written 2 beforeEach functions. One, to register the admin and the other one to Login the admin and get the token. I wonder if this is what is bringing the error? Please help

like image 439
Clint Dev Avatar asked Sep 02 '25 14:09

Clint Dev


2 Answers

I found the answer here:

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

You have to set { Authorization: "Bearer" + token } instead of "Authentication", token

You have to call .set after .get

 describe("/get users", () => {
    it("should fetch all users successfully", (done) => {
      chai
        .request(app)
        .get("/users")
        .set({ Authorization: `Bearer ${token}` })
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a("object");
          res.body.should.have.property("users");
          done();
        });
    });
  });
like image 153
andresf Avatar answered Sep 05 '25 11:09

andresf


chai-http has auth function to send the Authorization Bearer token.

Accroding to chai-http code on Github, token can be pass using:

.auth(accessToken, { type: 'bearer' })

An example provided on the similar Question: https://stackoverflow.com/a/66106588/4067905

like image 30
Keyul Avatar answered Sep 05 '25 13:09

Keyul