我正在嘗試爲以下函數編寫測試。使用Mocha.js測試預定義的回調函數
function services(api){
request(`${api}?action=services`, function(err, res, body) {
if (!err && res.statusCode === 200){
var resJson = JSON.parse(body);
var numberOfServices = resJson.length;
console.log("Service called: services");
console.log("-----------");
for (i = 0; i < numberOfServices; i++){
console.log("Service ID: " + resJson[i].service);
console.log("Service Name: " + resJson[i].name);
console.log("-----------");
}
return resJson;
}
});
}
測試正在檢查函數是否返回對象。 resJson
是要返回並測試的對象。
下面是使用Mocha.js和Chai.js聲明庫編寫的測試用例。
var chai = require('chai');
var assert = chai.assert;
var sendRequest = require('../request');
describe('Test 1', function() {
var api = 'http://instant-fans.com/api/v2';
it('services() should return an object of services', function(done) {
var object = sendRequest.services(api);
assert.isObject(object);
});
});
但是,當我運行測試時失敗,出現以下控制檯輸出。說resJson
是未定義的。我猜測,摩卡正試圖斷言resJson
是一個對象之前函數services()
返回對象,但我不知道如何解決這個問題。
Test 1
1) services() should return an object of services
0 passing (27ms)
1 failing
1) Test 1 services() should return an object of services:
AssertionError: expected undefined to be an object
at Function.assert.isObject (node_modules/chai/lib/chai/interface/assert.js:555:35)
at Context.<anonymous> (test/requestTest.js:11:16)
我曾嘗試這種在網上搜索,我看到人們解決這個使用done()
方法。但在我的情況下,這是行不通的,因爲我在services()
函數中使用了回調。
我是否將需要進行更改'服務()'函數? –
是的,正如我所說的,而不是做'返回resJson'你應該做'回調(resJson)'。這將確保您完成斷言。我編輯的答案與更新'services'功能 – piotrbienias
啊那是我第一次遇到的是,謝謝,你! :) –