目前我處理我的認證如下:節點貓鼬摩卡:如何在我的測試處理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