我试图测试$ http请求,无论我做什么,我似乎无法让它工作。我有一个工厂,它拥有4个请求类型GET,POST,PUT,DELETE。
我试图测试来自get请求的响应,但我在控制器中分配响应的scope变量给出了一个错误或undefined =来自get请求的响应。
工厂代码如下:
app.factory('requestService', ['$http', function ($http) {
// reusable requests
return {
//reuable get request
getRequest: function (url) {
return $http({
method: 'GET',
dataType: "json",
url: url
});
},
//reuable post request
postRequest: function (url, data) {
return $http({
method: 'POST',
data: data,
url: url
});
},
//reuable put request
putRequest: function (url, data) {
return $http({
method: 'PUT',
data: data,
url: url
});
},
//reuable delete request
deleteRequest: function (url) {
return $http({
method: 'DELETE',
url: url
});
}
}
}]);
以下是控制器中的内容。
//get the teams
$scope.getTeams = function(){
requestService.getRequest('https:.../teams').then(function (response) {
$scope.teams = response;
});
}
$scope.getTeams();
茉莉花代码:
describe('Controller Test', function() {
var $rootScope, controller;
//Tell the $httpBackend to respond with our mock object
var teamsResponse = {// Teams Data //};
beforeEach(function() {
module('myApp')
});
beforeEach(inject(function($rootScope, $controller, _$httpBackend_, $http) {
$scope = $rootScope.$new();
controller = $controller;
controller('Controller', {$scope: $scope});
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('https:...../teams').respond(200, teamsResponse);
}));
it('should load a list of teams', function() {
$scope.getTeams();
$httpBackend.flush();
expect($scope.teams).toBe(teamsResponse);
});
});
我得到的错误是:
预期未定义为{//团队数据//}
describe("Testing Common Get JSON Service", function () {
var service, $httpBackend;
beforeEach(inject(function($injector,$rootScope) {
service = $injector.get('CommonService');
$httpBackend = $injector.get('$httpBackend');
scope = $rootScope.$new();
successCallback = jasmine.createSpy();
errorCallback = jasmine.createSpy();
$httpBackend.when('GET', getFlightIncidentLookupUrl).respond(getFlightIncidentLookup);
successCallback();
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('test getServiceJSON works fine and calls a GET method', function () {
service.getServiceJSON(getFlightIncidentLookupUrl).then(function(response) {
expect(response.data.incidentLookup.length).toEqual(1);
});
$httpBackend.flush();
});
});
这对我有用。这里CommonService是Angular js中的一个服务,它调用get方法。我得到了正确的答复。