AngularJS中$routeChangeStart的Jasmine单元测试用例

嗨,我正在使用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?.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...