2017-08-17 226 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