Using $ httpBackend in a service when testing an Angular controller

I am trying to test a controller in my Angular framework:

.controller('UserCtrl', ['$scope', '$location', 'User', 'Config', function ($scope, $location, User, Config) { ... }]) 

This controller depends on several services that require the $ http object to invoke the server:

 .factory('User', ['$http', function ($http) { var data = {}; return { query: function(oper, putdata, callback){ if(oper == 'get'){ $http.get(getUrl("user",null)).success(function(data2) { console.log(data2); callback(data2); data.userinfo = data2; }); }, userinfo: data }; }]) 

But when I try to load the controller, I cannot get httpBackend to work:

 describe('UserCtrl', function(){ var ctrlScope, ctrl, $httpBackend, controllerService; beforeEach( inject(function($httpBackend, $http, $rootScope, $controller, User, Config) { _User = User; _Config = Config; spyOn(User, 'getUserInfo').andCallThrough(); //spyOn(User, 'query').andCallThrough(); ctrlScope = $rootScope.$new(); controllerService = $controller; httpMock = $httpBackend; }) ); it('should create setup userinfo object ', function() { httpMock.expectGET("/user/default/details"). respond({somejson}); ctrl = controllerService('UserCtrl', {$scope: ctrlScope, $location: location, User: _User, Config: _Config}); expect(_User.getUserInfo).toHaveBeenCalled(); httpMock.flush(); expect(ctrlScope.userinfo.length).toBe(1); }); }); 

All I ever get is:

 Error: No pending request to flush ! 

is it possible to use httpBackend with the service that you called from the controller that you are testing?

+6
source share
1 answer

Is there a reason you want to specifically test the GET request? This is the detailed information about your user service.

Regardless of whether your function is called query () or getUserInfo (), I suspect that all you really want to know is that the function was called in your user service. It depends on the user service to have their own set of tests that will verify that the GET request was made in / user / defaults / details.

The rationale for this is that you do not want the unit tests not related to it to be interrupted when the implementation of your User service changes. What happens when your API changes to /user/query ? UserCtrl tests should not be interrupted, and no other controller using the user service should be used. If your UserCtrl calls getUserInfo () on the user service, it is doing everything as correct as possible. User service tests will break, and as soon as you fix them to point to the new URL, everything will be back in order.

+1
source

Source: https://habr.com/ru/post/946073/


All Articles