2017-08-17 222 views
0

我想編寫單元測試用例,用於web API調用。單元測試不失敗

這都說明下面的成功:

Success Unit Test (jsfiddle)

 getProduct("jsonp","https://maps.googleapis.com/maps/api/e 

Error Unit Test (jsfiddle)但仍是其表演的 「通行證」

 getProduct("jsonp","https://sdfsdfdfmaps.googleapis.com/maps/api/e 

前一右的WebAPI網址:https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key

錯誤wepapi網址: https://sdfsdfdfmaps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key

即使wepapi網址錯誤。測試正在通過。

回答

1

刪除間諜功能,並添加fail回調,如果AJAX調用失敗,像這樣它會引發錯誤:

function getProduct(dataType,serviceURL,langCode ,callback) { 
    $.ajax({ 
     type: 'GET', 
     dataType: dataType, 
     url: serviceURL + langCode, 
     success: callback, 
     fail:() => { throw new Error('failed'); }, 
    }); 
} 

this fiddle here

但是這會導致實際的呼叫。爲了防止發生這種情況,請使用您的間諜功能並解析URL參數,如in this fiddle here

+0

謝謝!!但不適用於不同的服務,我需要改變以適用於其他服務?我需要改變任何木質基地? – SmartestVEGA

+0

謝謝我改變了它,並工作:) – SmartestVEGA