angularjs - 指令中的单元测试 $routeParams

标签 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 传递给指令。有办法做到这一点吗?

最佳答案

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

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

关于angularjs - 指令中的单元测试 $routeParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485655/

相关文章:

javascript - 前端应用程序的 Angular 路由

angularjs - 如何在 Angular/Jasmine 中模拟自定义过滤器

php - 如何检查模拟对象的方法不是仅使用特定参数调用的?

javascript - Angular 单元测试 : how to test controller properties without scope

javascript - 为什么这个 angularjs 指令不显示绑定(bind)文档?

android - 如何在 Android 应用程序中包含 Angular Material Design

angularjs 如何在重新加载页面后处理 $stateParams 变量

c# - 单元测试错误消息的内容?

javascript - 如何更改 IIS 默认网站的 angularJS 指令

angularjs - Angular 绑定(bind)指令的参数到 Controller