angularjs - 单元测试 AngularJS 指令

标签 angularjs unit-testing angularjs-directive

如何对我的指令进行单元测试?

我所拥有的是

angular.module('MyModule').
    directive('range', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                bindLow: '=',
                bindHigh: '=',
                min: '@',
                max: '@'
            },
        template: '<div><select ng-options="n for n in [min, max] | range" ng-model="bindLow"></select><select ng-options="n for n in [min, max] | range" ng-model="bindHigh"></select></div>'
    };
})

在我的单元测试中,我想从一个非常简单的测试开始
describe('Range control', function () {
    var elm, scope;

    beforeEach(inject(function(_$compile_, _$rootScope) {
        elm = angular.element('<range min="1" max="20" bind-low="low" bind-high="high"></range>');

        var scope = _$rootScope_;
        scope.low = 1;
        scope.high = 20;
        _$compile_(elm)(scope);
        scope.$digest();
    }));

    it('should render two select elements', function() {
        var selects = elm.find('select');

        expect(selects.length).toBe(2);
    });
});

这不起作用,因为该指令已在 app 模块上注册,并且我不想包含该模块,因为这将使我的所有 configrun代码运行。这将违背将指令作为一个单独的单元进行测试的目的。

我是否应该将所有指令放在一个单独的模块中并仅加载它?或者有没有其他聪明的方法来解决这个问题?

最佳答案

编辑:我看到自上次回答以来问题已经改变。

你需要把你的指令放在一个独立的模块中。

例如:

angular.module('MyModule.directives');

要仅测试该模块,您可以像这样在测试中显式加载该模块:
beforeEach(module('MyModule.directives'));

这将加载该模块及其所有依赖项。

请记住在应用程序的 MyModule 定义中将指令模块声明为依赖项:
angular.module('MyModule', ['MyModule.directives', ...]);

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

相关文章:

javascript - 指令如何等待处理元素的动态内插属性?

AngularJS 编写一个没有服务器的应用程序

ios - 字符串上的 XCTAssertEqual 总是失败

c# - Unitests 和 VS2012 Update 2 CTP 4 的问题

javascript单元测试变量和代码未封装在函数内

angularjs - 如何将 HTML 传递给 Angular 指令?

angularjs - 按不在 angularjs 中工作的顺序

javascript - 如何在 Angular JS 中加载页面?

javascript - 使用弹出框进行 Angularjs 验证

angularjs - Angular/ Jasmine : Error: No deferred tasks to be flushed