目前我处理我的认证如下:节点猫鼬摩卡:如何在我的测试处理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');
});
});
感谢您的反馈很多约翰内斯..你把我的轨道。作为事实上,我处理我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
现在解决了......感谢Johannes ..我现在正确地在我的express.js error_handler中处理了错误..需要检查与错误包使用!应该是es6错误,否则Babel不能正确处理instanceOf() – erwin