4
我有一個服務調用外部Web服務:Angular服務測試有什麼問題?
angular.module('myApp.services', [])
.service('autoCmpltDataSvc', function ($http) {
var innerMatch = function (data) {
return $.map(data, function (item) {
return {
fullName: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
shortName: item.name,
itemId: item.geonameId
};
});
};
this.fetchFromGeonamesDb = function (request, response, matcher) {
$http({
method: 'jsonp',
url: 'http://ws.geonames.org/searchJSON?callback=JSON_CALLBACK',
params: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.destName
}
}).success(function (data, status) {
console.log(data);
response($.map(innerMatch(data.geonames), matcher));
});
};
});
我試圖測試,它形成正確的輸出,所以我嘲笑調用真正的Web服務。 這是我的單元測試。
describe('Services', function() {
beforeEach(module('myApp.services'));
describe('autoCompleteService', function() {
var $httpBackend, svc;
var results = [];
var matcher = function (item) {
return item;
};
var response = function (arr) {
results = arr;
};
beforeEach(inject(function ($injector, autoCmpltDataSvc) {
svc = autoCmpltDataSvc;
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenJSONP(/searchJSON/).
respond([
{ name: 'City1', adminName1: 'Region1', countryName: 'Country1', geonameId: 1 },
{ name: 'City2', countryName: 'Country2', geonameId: 2}]);
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should return values', function() {
$httpBackend.expectJSONP(/searchJSON/);
svc.fetchFromGeonamesDb({ 'destName': 'fra' }, response, matcher);
$httpBackend.flush();
expect(results.length).toBe(2);
});
});
});
但是測試會產生錯誤。
TypeError: Cannot read property 'length' of undefined
at Function.v.extend.map (C:/Users/kmukhort/Documents/_files/TMate/A
ngularTest/app/lib/jquery-1.8.3.min.js:2:15334)
at innerMatch (C:/Users/kmukhort/Documents/_files/TMate/AngularTest/
app/js/services.js:8:18)
我想這是模擬響應錯誤,因爲它似乎不返回數組。 但我不明白爲什麼它不返回數組。
在此先感謝!
你的榜樣讓我嘲笑的服務。 Thx:D –