mardi 19 novembre 2019

Is there a way to test error handling in ExpressJS with Mocha when using a custom error handler?

Test

    it('should fail trying to GET bookmarks with false user id',async () => {
      try {
        const response = await request(app)
          .get(baseApiUrlUnderTest + 'false_user_id/bookmarks')
          .set('Authorization', bearerToken);
      } catch (e) {
        console.log(e); //it doesn't reach this point
        expect(e.httpStatus).to.equal(HttpStatus.CREATED);
      }
    });

The relevant part of the method under test:

/* GET bookmark of user */
personalBookmarksRouter.get('/', keycloak.protect(), wrapAsync(async (request, response) => {

  userIdTokenValidator.validateUserIdInToken(request);
 ...
}));

where wrapAsync makes sure the error is passed to the custom error handler:

let wrapAsync = function (fn) {
  return function(req, res, next) {
    // Make sure to `.catch()` any errors and pass them along to the `next()`
    // middleware in the chain, in this case the error handler.
    fn(req, res, next).catch(next);
  };
}

The validateUserIdInToken method which causes the method under test to throw an exception:

const AppError = require('../models/error');
const HttpStatus = require('http-status-codes');

let validateUserIdInToken = function (request) {
  const userId = request.kauth.grant.access_token.content.sub;
  if ( userId !== request.params.userId ) {
    throw new AppError(HttpStatus.UNAUTHORIZED, 'Unauthorized', ['the userId does not match the subject in the access token']);
  }
}

module.exports.validateUserIdInToken = validateUserIdInToken;

and the custom error handler in the root middleware:

app.use(function(err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  if(err instanceof AppError) { //execution lands here as expected and the test stops...
    res.status(err.httpStatus);
    return res.send(err);
  } else {
    res.status(err.status || HttpStatus.INTERNAL_SERVER_ERROR);
    res.send({
      message: err.message,
      error: {}
    });
  }

});

Aucun commentaire:

Enregistrer un commentaire