测试使用$location服务的痕迹导航指令



我正在尝试为面包屑指令/服务编写一个简单的单元测试。基本上,我想做的只是更改 location.path(或任何正确的方法),然后能够在指令的 HTML 上运行期望,以查看面包屑列表是否已更新。

breadcrumb service(借用自 AngularJS Breadcrumbs Service)看起来像这样:

var commonModule = angular.module('app.common');
commonModule.factory('common.service.breadcrumbs', ['$rootScope', '$location', function($rootScope, $location){
    var breadcrumbs = [];
    var breadcrumbsService = {};
    function setBreadcrumbs() {
        var pathElements = $location.path().split('/'), result = [], i;
        var breadcrumbPath = function (index) {
            return '/' + (pathElements.slice(0, index + 1)).join('/');
        };
        pathElements.shift();
        for (i=0; i<pathElements.length; i++) {
            result.push({name: pathElements[i], path: breadcrumbPath(i)});
        }
        breadcrumbs = result;
    }
    setBreadcrumbs();
    // We want to update breadcrumbs only when a route is actually changed
    // $location.path() will get updated immediately (even if route change fails!)
    $rootScope.$on('$routeChangeSuccess', function(event, current){
        setBreadcrumbs();
    });
    breadcrumbsService.getAll = function() {
        return breadcrumbs;
    };
    breadcrumbsService.getFirst = function() {
        return breadcrumbs[0] || {};
    };
    return breadcrumbsService;
}]);

我目前的测试如下所示:

describe("Directive:", function() {
    beforeEach(angular.mock.module("app"));
    var $compile,
        $scope,
        $location;
    // Angular strips the underscores when injecting
    beforeEach(inject(function(_$compile_, _$rootScope_, _$location_) {
        $compile = _$compile_;
        $scope = _$rootScope_.$new();
        $location = _$location_;
    }));
    describe("breadcrumbs", function () {
        it("correctly display the path as breadcrumbs.",
            inject(['common.service.breadcrumbs', function(breadcrumbs) {
                //console.log($location.path());
                //$scope.$apply();
                $location.path('/analyze/reports');
                $scope.$apply();
                //console.log($location.path());
                //console.log(breadcrumbs.getAll());
                $scope.$broadcast('$routeChangeSuccess', {});
                // Build the directive
                var element = $compile('<div class="cf-breadcrumbs" cf-breadcrumbs></div>')($scope);
                $scope.$apply();
                console.log(element.html());
            }]));
    });
});

目前,我从未看到面包屑服务更新面包屑数组。我试过 console.log(breadcrumbs.getAll()),它总是返回相同的数组,而没有两个新的路径元素。我担心这可能与时间有关,但不确定在我进行检查/应用之前,我将如何等待$routeChangeSuccess事件影响服务。

长话短说,我将如何测试以查看面包屑是否已适当更新?

测试

中$broadcast$rootScope。 $scope是$rootScope的子作用域,因为它是用$rootScope.$new()创建的,因此从该范围广播的事件不会向上移动到您附加$on处理程序的位置。

$broadcasts向下移动到子范围,而$emits向上移动。

最新更新