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

2024-04-19

嗨,我正在使用构建一个应用程序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 中得到类似的东西;

这是因为我没有在测试用例中涵盖这些语句,因为我不知道如何为这段特定的代码编写测试用例。有什么建议么?


That run每次加载模块时都会运行块,以便在测试期间注册侦听器。您只需要实际发送该事件,以便可以测试其中的代码。像这样的事情应该可以解决问题:

it("should test the $routeChangeStart listener", inject(function($rootScope) {
   $rootScope.$broadcast("$routeChangeStart");
   //expects for the listener
}));

See 如何测试角度事件? https://stackoverflow.com/questions/15272414/what-is-the-best-approach-to-test-events-in-angular/15282932了解如何测试一般事件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS 中 $routeChangeStart 的 Jasmine 单元测试用例 的相关文章

随机推荐