3

I'm using Express and Express-JWT.

In a Express() instance I use:

const api = express()
api.use(jwt({
 // my options
}))

To mock this in tests, I use a mocks\express-jwt\index.js file containing:

const jwt = jest.fn().mockImplementation(options => (req, res, next) => {
  // set dummy req.user and call
  next()
})

module exports = jwt

This all works fine. Now I want to skip JWT for the root endpoint, so I changed the jwt usage to:

api.use(jwt({
  // my options
}).unless({path:['/']}))

In my mock file I added:

jwt.unless = jest.fn().mockImplementation(options => (req, res, next) => {
  next()
})

However, the tests now always fail with function unless is not defined.

Anyone an idea how to mock this unless behaviour?

Joost den Boer
  • 4,556
  • 4
  • 25
  • 39

2 Answers2

1

unless is being used as a property on the result of calling jwt.

So to mock it, add your unless mock as a property of the function returned by your jwt mock:

const jwt = jest.fn().mockImplementation(options => {
  const func = (req, res, next) => {
    // set dummy req.user and call
    next();
  };
  func.unless = jest.fn().mockImplementation(options => (req, res, next) => {
    next();
  });
  return func;
});

module.exports = jwt;
Brian Adams
  • 43,011
  • 9
  • 113
  • 111
0

Suggested answer by Brian did not work for me, because in the func method I do some stuff for faking an authorization check. My problem was I needed to do skip the authorization check for the method+path given in by the unless function.

My solution now is like this:

const jet = jest.fn(options => {
  let mockFunc = (req, res, next) => {
    // get authorization from request
    let token = ...

    if (!token) {
      res.status(401).send('No token provided')
    } else {
      req.token = token
      next()
    }
  }

  mockFunc.unless = jest.fn(args => (req, res, next) => {
    if (args.method == req.method && arg.path == req.path) {
      // not do authorization check for excluded endpoint via unless
      next()
    else {
      mockFunc(req, res, next)
    }
  }

  return mockFunc
}

Thanks to Brian for pointing me in the right direction.

Joost den Boer
  • 4,556
  • 4
  • 25
  • 39