[英]Why error message is displayed on console when controller throws a method supertest
我正在為一個nodejs / sails js應用程序編寫集成測試,其中有一個異步控制器方法/路由,當不提供輸入參數時會引發錯誤。
我正在使用supertest編寫集成測試,從我的角度來看,一切正常,但是當測試運行錯誤寫入控制台時。
describe("a controller method", () => {
it("should throw error message", () => {
server('127.0.0.1')
.get('url to getData')
.set('Cookie', 'cookie token')
.end((err, res) => {
if(err) return done(err);
//console.log(res);
expect(res.status).to.equal(500);
expect(res.body).to.have.property('error', 'Provide a jobName');
done();
});
});
});
以下這段代碼可以正常工作,因為我將其包裝在一個匿名函數中,並希望該函數拋出。 但是我不確定如何斷言這些錯誤。
it("throws", () => {
expect( function () {
server('127.0.0.1')
.get('some url')
.set('Cookie', 'cookie token')
}).to.throw;
});
控制器代碼如下所示。 請求URL結束時正在調用的方法。
getData : async (req, res) => {
let jobName = req.params.jobName || '',
buildId = req.params.buildId || '';
if(!jobName.trim() ){
return res.negotiate({error:'Provide a jobName'});
}
if(isNaN(buildId)) {
return res.negotiate({error:'Invalid build id supplied.'});
}
try {
let rawResult = await getData(jobName, buildId);
let promotions = formatData(rawResult);
let result = {
total : promotions.length || 0,
items : promotions
};
return res.json(result);
} catch(error) {
sails.log.error(`Request Parameter: Job name = ${req.param('jobName')} & build id = ${req.param('buildId')}`);
sails.log.error(error);
return res.negotiate({error: sails.config.errorMessage});
}
}
為什么將錯誤寫入控制台? 我在這里做錯了什么? 任何幫助/指針,高度贊賞!
您如何通過快遞發送該錯誤? 通常,express遵循傳遞錯誤而不是拋出錯誤的方式,對於程序中的任何錯誤,您都可以將錯誤對象傳遞給'next'函數。 http://expressjs.com/en/guide/error-handling.html
例如
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
異步返回一個Promise,盡管您已經放置了try catch塊,但我的猜測是該塊中沒有錯誤。 這很可能是由於未處理承諾拒絕而引起的。
以下內容適用於Sails環境,對您有幫助。
由於異步函數返回一個Promise,因此您需要.catch()任何Promise拒絕並將它們傳遞給next()。 Express錯誤處理程序僅由傳遞給next()的錯誤觸發,而不由您引發的異常觸發。 資源
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.