AngularJS中$routeChangeStart的Jasmine单元测试用例
发布时间:2020-12-17 06:50:23 所属栏目:安全 来源:网络整理
导读:嗨,我正在使用AngularJS构建一个应用程序,现在我正在测试我的应用程序的单元.我知道如何为服务,控制器等编写单元测试用例.但我不知道为$routeChangeStart编写它. 我的app.js中有以下代码 app.run(function ($rootScope,$location,AuthenticationService) { $
嗨,我正在使用AngularJS构建一个应用程序,现在我正在测试我的应用程序的单元.我知道如何为服务,控制器等编写单元测试用例.但我不知道为$routeChangeStart编写它.
我的app.js中有以下代码 app.run(function ($rootScope,$location,AuthenticationService) { $rootScope.$on('$routeChangeStart',function () { if (AuthenticationService.isLoggedIn()) { $rootScope.Authenticated = 'true'; $rootScope.Identity = localStorage.getItem('identification_id'); } else { $rootScope.Authenticated = 'false'; $rootScope.Identity = localStorage.removeItem('identification_id'); } }); }); 我编写了这段代码,以确定用户是否已登录我的应用程序中的每个路由.我为此目的编写了一个服务AuthenticationService; app.factory('AuthenticationService',function (SessionService) { return { isLoggedIn: function () { return SessionService.get('session_id'); } }; }); 我的会话服务就像; app.factory('SessionService',function () { return { get: function (key) { return localStorage.getItem(key); } }; }); 我正在使用Jasmine编写测试用例并使用Istanbul进行代码覆盖.当我使用Grunt运行我的测试时,我在app.js中得到类似的东西; 这是因为我不在我的测试用例中覆盖这些语句,因为我不知道如何为这段特定的代码编写测试用例.有什么建议? 解决方法
每次加载模块时都会运行该运行块,以便在测试期间注册侦听器.您只需要实际发送该事件,以便可以测试其中的代码.像这样的东西应该做的伎俩:
it("should test the $routeChangeStart listener",inject(function($rootScope) { $rootScope.$broadcast("$routeChangeStart"); //expects for the listener })); 有关如何测试事件的一般信息,请参见How can I test events in angular?. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |