2017-05-28 94 views
0

目前我处理我的认证如下:节点猫鼬摩卡:如何在我的测试处理Promise.reject

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); 
    }); 
} 

我想有一个共同的APIERROR类

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; 
规范我的错误

如何在我的测试中测试Promise.reject?

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'); 
    }); 
}); 

回答

1

您根本没有处理错误/拒绝。您需要发送错误返回。我建议在express的路由末尾添加一个错误处理中间件,然后使用next(err)传递给它。

// at the end of your routes 
app.use(function(err, req, res, next) { 
    // do whatever you want, but at least send status and message: 
    res.status(err.status).json({ 
     message: err.message, 
    }); 
}); 

现在经过处理错误在你的路线:

.catch(() => { 
    const err = new APIError('Authentication error', httpStatus.UNAUTHORIZED, true); 
    return next(err); 
}); 
+0

感谢您的反馈很多约翰内斯..你把我的轨道。作为事实上,我处理我express.js文件中的错误。但是内接缝的APIERROR设置不正确... const err = new APIError('Authentication error',httpStatus.UNAUTHORIZED,true); ('CTLR err instanceof APIError?:',(err instanceof APIError)); return next(err); err未设置为APIError类实例...将检查为什么... – erwin

+0

现在解决了......感谢Johannes ..我现在正确地在我的express.js error_handler中处理了错误..需要检查与错误包使用!应该是es6错误,否则Babel不能正确处理instanceOf() – erwin

0

它现在运行良好,我在我的express.js错误处理的问题。作为APIERROR类型检查总是假的。 ..延长器ES6错误包,而不是错误解决这个问题通天...

APIError.js

import ExtendableError from 'es6-error'; // solve Babel issue w isInstanceOf() 
import httpStatus from 'http-status' 

class MyExtendableError extends ExtendableError { 
    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 MyExtendableError 
*/ 
class APIError extends MyExtendableError { 
    constructor(message, status = httpStatus.INTERNAL_SERVER_ERROR, isPublic = false) { 
    super(message, status, isPublic); 
    } 
} 

export default APIError; 

Express.js

// catch 404 and forward to error handler 
/* istanbul ignore next */ 
app.use((req, res, next) => { 
    const err = new APIError('API not found', httpStatus.NOT_FOUND); 
    return next(err); 
}); 

// if error is not an instance Of APIError, convert it. 
app.use((err, req, res, next) => { 
    if (err instanceof expressValidation.ValidationError) { 
    // validation error contains errors which is an array of error each containing message[] 
    const unifiedErrorMessage = err.errors.map((error) => { 
     return error.messages.join('. '); 
    }).join(' and '); 
    const error = new APIError(unifiedErrorMessage, err.status, true); 
    res.status(error.status).json({ 
     message: err.isPublic ? err.message : httpStatus[err.status], 
     stack: (config.env === 'test' || config.env === 'development') ? err.stack : {} 
    }); 
    } else if (!(err instanceof APIError)) { 
    const apiError = new APIError(err.message, err.status, err.isPublic); 
    res.status(apiError.status).json({ 
     message: err.isPublic ? err.message : httpStatus[err.status], 
     stack: (config.env === 'test' || config.env === 'development') ? err.stack : {} 
    }); 
    }else { 
    res.status(err.status).json({ 
    message: err.isPublic ? err.message : httpStatus[err.status], 
    stack: (config.env === 'test' || config.env === 'development') ? err.stack : {} 
    }); 
    } 
}); 

auth.route.js

import express from 'express'; 
import validate from 'express-validation'; 
import expressJwt from 'express-jwt'; 
import paramValidation from '../../../config/param-validation'; 
import authCtrl from '../controllers/auth.controller'; 
import config from '../../../config/config'; 

const router = express.Router(); 

/** POST /api/auth/login - Returns token if correct username and password is provided */ 
router.route('/login') 
    .post(validate(paramValidation.login), authCtrl.login); 

auth.controller.js

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 next(err); 
    }); 
} 

auth.test.js

.. 
    it('should return Authentication error',() => { 
     return request(app) 
     .post('/api/v1/auth/login') 
     .send(invalidUserCredentials) 
     .expect(httpStatus.UNAUTHORIZED) 
     .then((res) => { 
      expect(res.body.message).to.equal('Authentication error'); 
     }); 
    }); 
...