angularjs - Unit testing angular intercept -
is possible?
i can mock $httpbackend, , intercept called during $httpbackend.flush(); cannot hold of it. intercept function changes state of $rootscope, not help, because both on request , on response -- , state after response.
is there way check state of $rootscope after request? there way check state of config, input parameter?
here code:
// application // angular.module('myapp',[]); // // controller // var myapp = angular.module('myapp'); myapp.controller('fooctrl', ['$scope', '$http', function ($scope, _$http_) { var $http = _$http_; $scope.onsubmit = function() { var config = {method: 'post', url: '/foo.py', data: 'bar', myprop: 'request'}; $http(config).success(function(result) { }).error(function(data) { $scope.error = data; }); }; }]); // // service // var fooservice = angular.module('fooservice', ['ngresource']); fooservice.factory('foointercept', function ($q, $window, $log, $rootscope) { return { request: function (config) { $rootscope.myprop = config.myprop; config.headers = config.headers || {}; config.headers.authorization = 'session ' + $window.sessionstorage.sessionid; return config; }, response: function(response) { if($rootscope.myprop) { $rootscope.myprop = 'response'; } return response; }, responseerror : function(response) { if($rootscope.myprop) { $rootscope.myprop = 'error'; } var errormessage = response.config.errormessage; if(errormessage) { $window.alert(errormessage); } return $q.reject(response); } }; }); fooservice.config(function($httpprovider){ $httpprovider.interceptors.push('foointercept'); }); // // test // describe('trying mock httpbackend', function() { var $controller; var $httpbackend; var $rootscope; beforeeach(module('myapp')); beforeeach(module('fooservice')); beforeeach(inject(function ($injector) { $controller = $injector.get('$controller'); $httpbackend = $injector.get('$httpbackend'); $rootscope = $injector.get('$rootscope'); })); aftereach(function() { $httpbackend.verifynooutstandingexpectation(); $httpbackend.verifynooutstandingrequest(); }); it('not simple...', function() { var ctrl = $controller('fooctrl', {'$scope':$rootscope}); expect($rootscope.onsubmit).tobedefined(); $httpbackend.expectpost('/foo.py', 'bar').respond({username: 'fred', serveraddress: 'foo'}); $rootscope.onsubmit(); $httpbackend.flush(); expect($rootscope.myprop).tobe('request'); }); });
Comments
Post a Comment