单元测试AngularJS $窗口服务
发布时间:2020-12-17 07:38:15 所属栏目:安全 来源:网络整理
导读:我想单位测试以下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 re
我想单位测试以下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'}}); }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |