[英]Unit testing controller functions making external HTTP requests in NodeJS
大家好,所以我完全改寫了這個詞,並包括了我編寫的一些代碼。 通常,我會先對此進行測試,但是我對如何實現此方法一無所知。
我想從此功能的單元測試開始。
exports.getMatches = function(callback) {
var url = "http://football-api.comapi/?Action=today&APIKey=" + secrets.APIKey + "&comp_id=1204";
async.waterfall([
function(callback) {
request(url, function (error, response, body) {
if (error) return (error);
var parsedJSON = JSON.parse(body);
var todaysMatches = parsedJSON.matches;
var schedule = new Schedule({
date: dates.today // external module
matches: []
});
_.each(todaysMatches, function (match) {
schedule.matches.push({
match_id: match.match_id,
match_time: match.match_time,
match_localteam_id: match.match_localteam_id,
match_localteam_name: match.match_localteam_name,
match_visitorteam_id: match.match_visitorteam_id,
match_visitorteam_name: match.match_visitorteam_name
});
});
callback(schedule);
});
}
], function(schedule) {
schedule.save(function (err) {
if (err) return (err);
});
done();
});
};
我很抱歉沒有提供任何進展,因為我在這里只是一個精神障礙。 只有幾行代碼,但是有太多的事情正在進行,要測試的東西太多,所以我不確定從哪里開始/要模擬什么/如何模擬它。
聽起來您要測試request()
而不是實際的控制器方法。
您的單元測試應該評估傳遞給list()
回調的所有內容,並確定是否已對其進行了相應的轉換。
例如,如果list()
將JSON數組轉換為HTML列表<ul><li /><li />...</ul>
,則應測試響應/正文輸出以確定轉換是否成功。
var mockJSON = [{id: 1, name: 'spinach'}];
var expected = '<ul><li data-id="1">spinach</li></ul>';
//...
matchController.list(function (error, response, body) {
// something like this...
expect(body).to.equal(expected);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.