指令中的单元测试 $routeParams

Unit Testing $routeParams in directive

我有一个访问页面 $routeParams 的指令:

myApp.directive("myList", function ($routeParams) {
    return {
        restrict: 'E',
        templateUrl: 'tabs/my-list.html',
        link: function (scope) {
            scope.year = $routeParams.year;
       }
    };
});

该指令按预期工作并正确访问 $routeParams

我正在尝试使用 angular-mock/jasmine 进行测试。我不知道如何将 mock $routeParams 传递给指令。这是我的:

describe('myList', function () {
    var scope, compile, element, compiledDirective;
    var mockParams = { 'year': 1996 };

    beforeEach(function () {
        module('templates', 'MyApp');

        inject(function ($compile, $rootScope, $routeParams) {
            compile = $compile;
            scope = $rootScope.$new();
        });
        element = angular.element('<my-list></my-list>');
        compiledDirective = compile(element)(scope);
        scope.$digest();
    });
    it('should fill in the year', function () {
        expect(scope.year).toEqual(mockParams.year);
    });
});

这显然是行不通的,因为我从未将 passed mockParams 传递给指令。有办法吗?

模拟 $routeParams 对象 mockParams 使用 angular.extend mockParams 对象直接分配给 $routeParams .这样 $routeParams 将在编译指令之前可用。

inject(function ($compile, $rootScope, $routeParams) {
    compile = $compile;
    scope = $rootScope.$new();
    angular.extend($routeParams, mockParams);
});