我想单位测试以下AngularJs服务:
.factory('httpResponseInterceptor',['$q','$location','$window','CONTEXT_PATH',function($q,$location,$window,contextPath){ return { response : function (response) { //Will only be called for HTTP up to 300 return response; },responseError: function (rejection) { if(rejection.status === 405 || rejection.status === 401) { $window.location.href = contextPath + '/signin'; } return $q.reject(rejection); } }; }]);
我尝试过以下套件:
describe('Controllers',function () { var $scope,ctrl; beforeEach(module('curriculumModule')); beforeEach(module('curriculumControllerModule')); beforeEach(module('curriculumServiceModule')); beforeEach(module(function($provide) { $provide.constant('CONTEXT_PATH','bignibou'); // override contextPath here })); describe('CreateCurriculumCtrl',function () { var mockBackend,location,_window; beforeEach(inject(function ($rootScope,$controller,$httpBackend,$window) { mockBackend = $httpBackend; location = $location; _window = $window; $scope = $rootScope.$new(); ctrl = $controller('CreateCurriculumCtrl',{ $scope: $scope }); })); it('should redirect to /signin if 401 or 405',function () { mockBackend.whenGET('bignibou/utils/findLanguagesByLanguageStartingWith.json?language=fran').respond([{"description":"Français","id":46,"version":0}]); mockBackend.whenPOST('bignibou/curriculum/new').respond(function(method,url,data,headers){ return [401]; }); $scope.saveCurriculum(); mockBackend.flush(); expect(_window.location.href).toEqual("/bignibou/signin"); }); }); });
PhantomJS 1.9.2 (Linux) Controllers CreateCurriculumCtrl should redirect to /signin if 401 or 405 Failed Expected 'http://localhost:9876/context.html' to equal '/bignibou/signin'. PhantomJS 1.9.2 (Linux) ERROR Some of your tests did a full page reload!
我不知道发生了什么问题,为什么.有人可以帮忙吗?
我只是想确保$window.location.href等于’/ bignibou / signin’.
编辑1:
我设法让它工作如下(感谢“dskh”):
beforeEach(module('config',function($provide){ $provide.value('$window',{location:{href:'dummy'}}); }));
您可以在加载模块时注入存根依赖项:
angular.mock.module('curriculumModule',function($provide){ $provide.value('$window',{location:{href:'dummy'}}); });