在AngularJS茉莉花单元测试用例$ routeChangeStart茉莉花、单元测试、AngularJS、routeChangeStart

2023-09-13 04:51:56 作者:_说爱我就别伤害我

嗨我建立使用 AngularJS 的应用程序,现在我到单元测试我的应用程序。我知道如何编写单元测试用例的服务,控制器等,但我不知道把它写在 $ routeChangeStart

Hi I am building an app using AngularJS and now I am on to the unit testing my application. I know how to write unit test cases for services, controllers etc. But I don't know to write it for $routeChangeStart.

我在app.js以下code

I have following code in my 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');
        }
    });
});

我写了这个code找出用户是否登录或不适合在每次我的应用程序的路由。我写了一个服务的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);
        }
    };
});

我使用茉莉花来编写测试用例,并使用伊斯坦布尔为code覆盖。当我用我的运行测试步兵我收到我的app.js这样的事情;

I am using Jasmine to write test cases and using Istanbul for code coverage. When I run my test using Grunt I am getting something like this in my app.js;

这是因为我没有覆盖在我的测试情况下,这些语句,因为我不知道怎么写测试用例这件特定的code的。有什么建议?

It's because I am not covering these statements in my test cases as I don't know how to write test case for this particular piece of code. Any suggestions?

推荐答案

这是运行块运行的每个模块被加载时,使监听器在测试期间被注册。你只需要该事件实际被发送,这样就可以在它测试code。这样的事情应该做的伎俩:

That run block runs every time the module is loaded, so that listener is being registered during the tests. You just need that event to actually be sent so that you can test the code within it. Something like this should do the trick:

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

请参阅What是测试事件的角度,最好的办法?了解如何在通用测试活动。

See What is the best approach to test events in angular? for how to test events in general.