Sunday, March 19, 2017

Testing a jsonwebtoken authentication express middleware

Leave a Comment

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

Answers 1

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment