单元测试指令中的$ routeParams

时间:2016-04-07 19:38:37

标签: angularjs unit-testing angularjs-directive jasmine angular-mock

我有一个指令可以访问页面的$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进行测试。我无法弄清楚如何将模拟$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);
    });
});

这显然不起作用,因为我从未将mockParams传递给指令。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:3)

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

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