Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a jsonwebtoken authentication express middleware

I am currently learning to do testing in general and I am not sure how one tests an express middleware that authenticates a jsonwebtoken. An express middleware is basically a function so in theory it should be unit testable. Could someone show me how one would do so? Here is my middleware so far. I am currently using mocha and chai as my testing framework.

import jwt from "jsonwebtoken";
import secret from "../jwtSecret"

function authenticateJwt(req, res, next){
  let token;
  let authorizationHeaders = req.headers["authorization"];
  if(authorizationHeaders){
    token = authorizationHeaders.split(" ")[1];
  }
  if(token) {
    jwt.verify(token, secret, (err, decodedToken) => {
      if(err){
        res.status(403).json({
          success: false,
          error: "Invalid token provided"
        });
      } else {
        next();  
      }
    });
  } else {
    res.status(403).json({
      success: false,
      error: "No token provided"
    });
  }
}

export default authenticateJwt;

1 Answers

Well, by testing the input and output you could test a function. In this case, req/res/next is the input. But instead of return, res.status(403).json() and next() comes as the result of your middleware(or output).

So by mocking req/res/next, you will be at full control of the input and output. As follow.

describe('middleware/auth', ()=> {
  let mockReq = {
    headers:{} // your JWT here
  }
  let mockRes = {
    status = function(code){return 'status${code}'}
  }
  let nextCalled = false;
  let next = function(){nextCalled = true}

  it('should pass on right jwt',()=>{
    mockReq.headers['JWT'] = 'right jwt'
    authenticateJwt(mockReq, mockRes, next)
    expect(nextCalled).to.be.true;
  })
})

But using additional variables like nextCalled is not the best choice. Sinon or other spies might be better.

like image 96
YLS Avatar answered Aug 03 '26 21:08

YLS



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!