Tuesday, 14 March 2017

Sinon spy not being called inside an express middleware

I'm currently learning to test a jwt authentication express middleware. My next callback is being called because i put a console.log there but my sinon spy assertion is failing.

Can someone take a look at this case?

This is my test case

  it("should call next when the token provided is valid", () => {
    let token = jwt.sign({}, process.env.JWT);
    let request = httpMocks.createRequest({
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    const next = sinon.spy();
    authenticateJwt(request, response, next);
    expect(next.calledOnce).to.be.true;
  });

And here is my middleware

import jwt from "jsonwebtoken";

export default function(req, res, next){
  const authorizationHeaders = req.headers["authorization"];
  let token;

  if(authorizationHeaders){
    token = authorizationHeaders.split(" ")[1];
  }

  if(token){
    jwt.verify(token, process.env.JWT, (err, decodedToken) => {
      if(err){
        res.status(401).json({
          message: "invalid token provided"
        });
      } else {
        res.user = decodedToken;
        console.log("called");
        next();
      }
    });
  } else {
    res.status(401).json({
      success: false,
      message: "no token provided"
    });
  }
}

My console.log is logging correctly but the sinon assertion is failing.



via Nate

No comments:

Post a Comment