Sunday 28 May 2017

node mongoose mocha : how to handle a Promise.reject in my test

Currently I handle my authentication as following :

function login(req, res, next) {
  // fetch user from the db
  User.findOne(req.body)
    .exec()   // make query a Promise
    .then((user) => {
      const token = jwt.sign({ username: user.username }, config.jwtSecret);
      return res.json({ token, username: user.username });
    })
    .catch(() => {
      const err = new APIError('Authentication error', httpStatus.UNAUTHORIZED, true);
      return Promise.reject(err);
    });
}

I am trying to standardize my errors with a common APIError class

import httpStatus from 'http-status';

/**
 * @extends Error
 */
class ExtendableError extends Error {
  constructor(message, status, isPublic) {
    super(message);
    this.name = this.constructor.name;
    this.message = message;
    this.status = status;
    this.isPublic = isPublic;
    this.isOperational = true; // This is required since bluebird 4 doesn't append it anymore.
    Error.captureStackTrace(this, this.constructor.name);
  }
}

/**
 * Class representing an API error.
 * @extends ExtendableError
 */
class APIError extends ExtendableError {
  /**
   * Creates an API error.
   * @param {string} message - Error message.
   * @param {number} status - HTTP status code of error.
   * @param {boolean} isPublic - Whether the message should be visible to user or not.
   */
  constructor(message, status = httpStatus.INTERNAL_SERVER_ERROR, isPublic = false) {
    super(message, status, isPublic);
  }
}

export default APIError;

How can I test the Promise.reject in my test ?

describe('# POST /api/v1/auth/login', () => {
it('should return Authentication error', () => {
  return request(app)
    .post('/api/v1/auth/login')
    .send(invalidUserCredentials)
     // following lines are not valid anymore with Promise.reject ..
    .expect(httpStatus.UNAUTHORIZED)
    .then((res) => {
      expect(res.body.message).to.equal('Authentication error');
    });
});



via erwin

No comments:

Post a Comment