您应该使用最新的语法来构造拦截器定义。您的URL构造也应包含在服务中,以便可以在测试中轻松模拟它。
.factory('UnauthorizedInterceptor', function($q, $window, OtherService) { var service = { responseError: handleUnauthorized }; return service; function handleUnauthorized(rejection) { if (rejection.status === 401) { $window.location.href = OtherService.getUnauthorizedRedirectURL(); } return $q.reject(rejection); }});这样做可以让您像其他任何工厂一样对其进行测试,而不必担心
$http拦截器的内部实现,也不必使用来模拟响应
$httpBackend。
describe('Domain.handlers.response', function() { var $window, UnauthorizedInterceptor, OtherService, redirectUrl = 'someUrl'; beforeEach(module('Domain.handlers')); beforeEach(function () { $window = { location: { href: null } }; module(function($provide) { $provide.value('$window', $window); }); }); beforeEach(inject(function(_UnauthorizedInterceptor_, _OtherService_) { UnauthorizedInterceptor = _UnauthorizedInterceptor_; OtherService = _OtherService_; spyOn(OtherService, 'getUnauthorizedRedirectURL').andReturn(redirectUrl); })); describe('UnauthorizedInterceptor', function() { it('should be defined', function() { expect(UnauthorizedInterceptor).toBeDefined(); }); it('should have a handler for responseError', function () { expect(angular.isFunction(UnauthorizedInterceptor.responseError)).toBe(true); }); describe('when HTTP 401', function () { beforeEach(function () { var rejection = { status: 401 }; UnauthorizedInterceptor.responseError(rejection); }); it('should set window location', function () { expect($window.location.href).toBe(redirectUrl); }); }); describe('when not HTTP 401', function () { beforeEach(function () { var rejection = { status: 500 }; UnauthorizedInterceptor.responseError(rejection); }); it('should not set window location', function () { expect($window.location.href).not.toBe(redirectUrl); }); }); });});


