我试图测试我的响应拦截器,但我很难搞清楚如何模拟$窗口对象。这里是我的代码拦截器:角度茉莉花测试响应拦截器
'use strict';
angular.module('Domain.handlers')
.config(function($httpProvider) {
$httpProvider.responseInterceptors.push('UnauthorizedInterceptor');
})
.factory('UnauthorizedInterceptor', function($q, $injector, $window, ENV) {
return function(promise) {
var success = function(response) { return response; };
var error = function(response) {
if (response.status === 401) {
$window.location.href = ENV.account + '/oauth/authorize?client_id=' + ENV.clientId + '&redirect_uri=' + ENV.app + '/oauth/callback&response_type=token';
}
return $q.reject(response);
};
return promise.then(success, error);
};
});
这里是我的规格:
'use strict';
describe('Domain.handlers.response', function() {
var UnauthorizedInterceptor,
httpProvider,
$httpBackend,
$http,
token = '123456789';
beforeEach(module('Domain.handlers', function($httpProvider) {
httpProvider = $httpProvider;
}));
beforeEach(inject(function(_UnauthorizedInterceptor_, _$httpBackend_, _$http_) {
UnauthorizedInterceptor = _UnauthorizedInterceptor_;
$httpBackend = _$httpBackend_;
$http = _$http_;
}));
describe('UnauthorizedInterceptor', function() {
it('should be defined', function() {
expect(UnauthorizedInterceptor).toBeDefined();
});
describe('HTTP status', function() {
describe('is 200 OK', function() {
it('should return a 200 status', function() {
$httpBackend.expectGET('http://api.domain.com/clients').respond(200, {});
$http.get('http://api.domain.com/clients');
$httpBackend.flush();
});
});
describe('is 401 Unauthorized', function() {
it('should redirect to accounts.domain.com', inject(function($window) {
$httpBackend.expectGET('http://api.domain.com/clients').respond(401, {});
$http.get('http://api.domain.com/clients');
expect($window.location.href).toEqual('http://accounts.domain.com/oauth/.....');
$httpBackend.flush();
}));
});
});
});
});
我有一个:Expected 'http://localhost:8080/context.html' to equal 'http://accounts.domain.com/oauth/.....'
。有关如何正确模拟$ window对象或更一般地如何测试401 +重定向情况的任何帮助?
非常感谢您的回答。它帮助我理解了一些我不知道的东西。但是,我仍然遇到'Expected'http:// localhost:8080/context.html'为'http://dev-accounts.domain.dev:3000/oauth/authorize ...'的错误。我认为这与'$ window.location.href'有关,它总是返回'http:// localhost:8080/context.html'。有任何想法吗? – lkartono 2014-11-25 12:20:46
你在什么浏览器中运行测试? – user2943490 2014-11-25 12:26:34
我正在使用PhantomJs – lkartono 2014-11-25 12:27:15