unit-testing - 包含routeChangeSuccess的AngularJS测试 Controller

标签 unit-testing angularjs

我正在尝试创建单元测试来测试导航列表 Controller ,但在创建测试时遇到问题。

这是 Controller 的代码。

navListModule.controller('NavListCtrl', ['$scope', 'NavList',
    function ($scope, NavList) {
        $scope.$on('$routeChangeSuccess', function (event, routeData) {
            var stationId = routeData.params.stationId;

            if ((stationId !== null) && (stationId !== undefined)) {
                $scope.stationId = stationId;
                var navList = NavList;
                $scope.menuOptions = navList.getMenuOptions(stationId);
            }
        });
    }
]);

这是我迄今为止在单元测试中得出的结论。

'use strict';

describe('unit testing navListModule', function () {

    var scope, ctrl, location;

    describe('test NavListCtrl', function () {

        beforeEach(module('shipApp.navListModule'));

        // mock NavListService for testing purposes
        var mockNavListService = {
            getMenuOptions: function (stationId) {
                // set default menu options
                var menuOptions = [
                    {
                        name: "Alerts"
                        , pageURL: "alerts"
                    }
                    , {
                        name: "Reports"
                        , pageURL: "reports"
                    }
                    , {
                        name: "Run Close Outs"
                        , pageURL: "closeOuts"
                    }
                ];

                // add admin menu option if stationId set to Admin
                if (stationId.toUpperCase() == 'Admin'.toUpperCase()) {
                    menuOptions.push(
                        {
                            name: "Admin"
                            , pageURL: "admin"
                        }
                    );
                }

                return menuOptions;
            }
        };

        beforeEach(inject(function ($rootScope, $controller, $location) {
            scope = $rootScope.$new();
            ctrl = $controller('NavListCtrl', { $scope: scope, NavList: mockNavListService });
            location = $location;
        }));

        it('should expect stationId to be undefined if stationId not defined in route parameters', function () {
            expect(scope.stationId).toBeUndefined();
        });

        it('should expect scope.$on not to be called if no change in route', function () {
            spyOn(scope, '$on');
            expect(scope.$on).not.toHaveBeenCalled();
        });

        it('should expect scope.$on to be called on change in route', function () {
            spyOn(scope, '$on');
            scope.$on('$routeChangeSuccess', function (event, routeData) {});
            expect(scope.$on).toHaveBeenCalled();
        });

        it('should expect stationId to be defined in route parameters if route is #/:stationId/path', inject(function ($routeParams) {
            location.path('/Admin/alerts');
            var locationElements = location.path().substring(location.path().indexOf('/') + 1).split('/');
            var stationId = locationElements[0];
            $routeParams.stationId = stationId;
            expect($routeParams.stationId).toEqual('Admin');
        }));

        it('should expect menuOptions array to be returned when getMenuOptions function is called', function () {
            var stationId = 'Admin';
            var menuOptions = NavListCtrl.getMenuOptions(stationId);
        });

    });

});

我刚刚学习 Angular,所以我不确定我是否正确设置了测试。我是否应该创建测试以确保 Controller 逻辑在 $routeChangeSuccess 事件发生之前不会发生?如果是这样,我该如何编写这样的测试?另外,测试 getMenuOptions 调用(上次测试)的正确方法是什么?请让我知道测试该 Controller 的正确方法。

提前致谢, 肖恩

在进行了一些测试并获得了 jvandemo 的帮助后,以下是我针对 Controller 以及底层服务的单元测试得出的结论。如果我做错了什么,请告诉我。

'use strict';

describe('unit testing navListModule', function () {

    beforeEach(module('shipApp.navListModule'));

    /***** Controllers *****/

    describe('test NavListCtrl', function () {

        var ctrl, scope, NavList, $httpBackend, $location, $route, $routeParams;

        // mock the http backend for routing
        beforeEach(module(function() {
            return function(_$httpBackend_) {
                $httpBackend = _$httpBackend_;
                $httpBackend.when('GET', 'views/alerts/alerts.html').respond('alerts');
                $httpBackend.when('GET', 'views/alerts/reports.html').respond('reports');
                $httpBackend.when('GET', 'views/alerts/closeOuts.html').respond('closeOuts');
                $httpBackend.when('GET', 'views/alerts/admin.html').respond('admin');
                $httpBackend.when('GET', 'views/shared/error.html').respond('not found');
            };
        }));

        // add $routeProvider mock
        beforeEach(module(function ($routeProvider) {
            $routeProvider.when('/:stationId/alerts', {
                templateUrl : 'views/alerts/alerts.html',
                controller : 'AlertsCtrl'
            });
            $routeProvider.when('/:stationId/reports', {
                templateUrl : 'views/reports/reports.html',
                controller : 'ReportsCtrl'
            });
            $routeProvider.when('/:stationId/closeOuts', {
                templateUrl : 'views/closeOuts/closeOuts.html',
                controller : 'CloseOutsCtrl'
            });
            $routeProvider.when('/:stationId/admin', {
                templateUrl : 'views/admin/admin.html',
                controller : 'AdminCtrl'
            });
            $routeProvider.when('/404', {
                templateUrl : 'views/shared/error.html',
                controller : 'ErrorCtrl'
            });
            $routeProvider.when('/', {
                redirectTo : '/MasterPl/alerts'
            });
            $routeProvider.when('/:stationId', {
                redirectTo : '/:stationId/alerts'
            });
            $routeProvider.when(':stationId', {
                redirectTo : '/:stationId/alerts'
            });
            $routeProvider.when('', {
                redirectTo : '/MasterPl/alerts'
            });
            $routeProvider.otherwise({
                redirectTo: '/404'
            });
        }));

        beforeEach(inject(function ($rootScope, $controller, _$location_, _$route_, _$routeParams_) {
            // mock NavList service
            var mockNavListService = {
                getMenuOptions: function (stationId) {
                    // set default menu options
                    var menuOptions = [
                        {
                            name: "Alerts"
                            , pageURL: "alerts"
                        }
                        , {
                            name: "Reports"
                            , pageURL: "reports"
                        }
                        , {
                            name: "Run Close Outs"
                            , pageURL: "closeOuts"
                        }
                    ];

                    // add admin menu option if stationId set to Admin
                    if (stationId.toUpperCase() == 'Admin'.toUpperCase()) {
                        menuOptions.push(
                            {
                                name: "Admin"
                                , pageURL: "admin"
                            }
                        );
                    }

                    return menuOptions;
                }
            };


            NavList = mockNavListService;
            scope = $rootScope.$new();
            $location = _$location_;
            $route = _$route_;
            $routeParams = _$routeParams_;
            ctrl = $controller('NavListCtrl', { $scope: scope, $routeParams: $routeParams, NavList: NavList });
        }));

        it('should expect stationId and menuOptions to be undefined if stationId not defined in route parameters', function () {
            expect(scope.stationId).toBeUndefined();
            expect(scope.menuOptions).toBeUndefined();
        });

        it('should expect scope.$on not to be called if no change in route', function () {
            spyOn(scope, '$on');
            expect(scope.$on).not.toHaveBeenCalled();
        });

        it('should expect scope.$on to be called on change in route', function () {
            spyOn(scope, '$on');
            scope.$on('$routeChangeSuccess', function (event, routeData) {});
            expect(scope.$on).toHaveBeenCalled();
        });

        it('should not parse $routeParameters before $routeChangeSuccess', function () {
            $location.path('/Admin/alerts');
            scope.$apply();
            expect(scope.stationId).toBeUndefined();
        });

        it('should expect scope values to be set after $routeChangeSuccess is fired for location /stationId/path', function () {
            $location.path('/Admin/alerts');
            scope.$apply();
            $httpBackend.flush();
            expect(scope.stationId).toEqual('Admin');
            expect(scope.menuOptions).not.toBeUndefined();
        });

        it('should expect NavList.getMenuOptions() to have been called after $routeChangeSuccess is fired for location /stationId/path', function () {
            spyOn(NavList, 'getMenuOptions').andCallThrough();
            $location.path('/Admin/alerts');
            scope.$apply();
            $httpBackend.flush();
            expect(NavList.getMenuOptions).toHaveBeenCalled();
            expect(scope.menuOptions.length).not.toBe(0);
        });

    });


    /***** Services *****/

    describe('test NavList service', function () {

        var scope, NavList;

        beforeEach(inject(function ($rootScope, _NavList_) {
            scope = $rootScope.$new();
            NavList = _NavList_;
        }));

        it('should expect menuOptions array to be returned when getMenuOptions function is called', function () {
            var stationId = 'Admin';
            var menuOptions = NavList.getMenuOptions(stationId);
            expect(menuOptions.length).not.toBe(0);
        });

        it('should expect admin menu option to be in menuOptions if stationId is Admin', function () {
            var stationId = 'Admin';
            var menuOptions = NavList.getMenuOptions(stationId);
            var hasAdminOption = false;
            for (var i = 0; i < menuOptions.length; i++) {
                if (menuOptions[i].name.toUpperCase() == 'Admin'.toUpperCase()) {
                    hasAdminOption = true;
                    break;
                }
            }
            expect(hasAdminOption).toBe(true);
        });

        it('should not expect admin menu option to be in menuOptions if stationId is not Admin', function () {
            var stationId = 'MasterPl';
            var menuOptions = NavList.getMenuOptions(stationId);
            var hasAdminOption = false;
            for (var i = 0; i < menuOptions.length; i++) {
                if (menuOptions[i].name.toUpperCase() == 'Admin'.toUpperCase()) {
                    hasAdminOption = true;
                    break;
                }
            }
            expect(hasAdminOption).toBe(false);
        });

    });

});

最佳答案

您在测试中已经做得很好了。我假设您的测试运行正确(除了最后一个测试),并将分别回答您的两个问题:

  1. $routeChangeSuccess:您无需测试核心 AngularJS 功能。当您依赖 $routeChangeSuccess 在某个时刻运行代码时,AngularJS 团队及其测试套件有责任确保 $routeChangeSuccess 正常工作。

  2. getMenuOptions():由于此方法是您要注入(inject)的服务的一部分,因此您可以创建一个单独的单元测试来测试 NavList 服务并移动该套件的最后一次测试。由于您正在进行单元测试,因此最好为每个组件( Controller 、服务等)创建单独的测试套件,以保持良好的组织性和紧凑性。

希望有帮助!

关于unit-testing - 包含routeChangeSuccess的AngularJS测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17236809/

相关文章:

java - 使用 Mockito 验证多个方法调用的顺序

c# - 使用 NUnit 和 C# 对异步方法进行单元测试

unit-testing - Vue Test Utils 中的 "stubbed child components"是什么?

ios - 将测试目标的 'Host Application' 设置为 None,然后无法找到捆绑资源

javascript - 从 JSON 数据中以 Angular 填充多个下拉选择框

reactjs - 我应该测试相反的情况吗?

javascript - 获取 Angular ng-option 下拉列表的选定文本

javascript - 无法从 child 那里获取 CSS 属性?

javascript - 将 md-switch 转换为 md-select

javascript - Angular Controller 与服务的通信