单元测试AngularJS $窗口服务

bal*_*teo 14 angularjs

我想对以下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);
         }
     };
}]);
Run Code Online (Sandbox Code Playgroud)

我尝试过以下套件:

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, $location, $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");
        });


    });
});
Run Code Online (Sandbox Code Playgroud)

但是,它失败并显示以下错误消息:

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!
Run Code Online (Sandbox Code Playgroud)

我不确定出了什么问题,为什么.有人可以帮忙吗?

我只想确保 $window.location.href等于'/bignibou/signin'.

编辑1:

我设法让它按如下方式工作(感谢"dskh"):

 beforeEach(module('config', function($provide){
      $provide.value('$window', {location:{href:'dummy'}});
 }));
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 17

在模块中加载时,可以注入存根依赖项:

angular.mock.module('curriculumModule', function($provide){
            $provide.value('$window', {location:{href:'dummy'}});
        });
Run Code Online (Sandbox Code Playgroud)