我一直在嘗試使用摩卡測試下面的代碼,但我總是得到錯誤。摩卡測試承諾
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test
我想測試的代碼如下。
'use strict'
const Promise = require('bluebird');
const successResponse = {status: 'OK'};
const failResponse = {status: 'FAIL'};
function dbStatusSuccess() {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(successResponse);
}, 2010);
});
}
function dbStatusFail() {
return new Promise(function(resolve, reject) {
setTimeout(() => {
reject(failResponse);
}, 2000);
});
}
module.exports = {
dbStatusSuccess,
dbStatusFail
}
這裏是我的測試。
'use strict'
const Promise = require('bluebird');
const chai = require('chai')
chai.use(require('chai-string'))
chai.use(require('chai-as-promised'));
const expect = chai.expect;
chai.should();
const healthyCheck = require('./healthyCheck');
const resp = {status:'OK'};
const resp2 ={status: 'FAIL'};
describe('healthy-check end point',() => {
it('should return successful response when connected to database',() => {
return healthyCheck.dbStatusSuccess()
.then((res) => {
console.log(JSON.stringify(res, undefined, 2));
return expect(res).to.equal(resp);
}).catch((err) => {
console.log(err);
return expect(err).to.deep.equal(resp2);
});
});
});
我也得到一個錯誤{Asse田:在控制檯 'OK'} {預期狀態: 'OK'}等於{地位。我相信它是從.catch函數中的錯誤記錄中提取出來的。
編輯1. 從dbStatusSuccess函數中刪除了拒絕函數。
問題在於承諾花費2秒完成/失敗。如果setTimeout中設置的時間少於2秒,測試將通過。
我發現一個問題,如果你的代碼,你爲什麼在函數dbStatusSuccess()中調用resolve()和reject()? – iKoala
這是一個錯誤。我已經刪除了。但我不明白這會如何影響承諾的運作方式?問題是超時錯誤,即使我使用從它傳遞的done()函數,或者如果我返回承諾,我也會得到這個錯誤 – AshanPerera
它會給出預期的結果,因爲承諾不能同時解析和拒絕。 – iKoala