【问题标题】:Unit testing an AngularJS (Smart Table) directive对 AngularJS(智能表)指令进行单元测试
【发布时间】:2015-02-16 12:03:45
【问题描述】:

我正在使用“智能表”并将使用他们的示例插件,其中复选框选择表中的一行:http://lorenzofox3.github.io/smart-table-website/#section-custom

我正在为这个指令编写一个单元测试,代码如下,这是失败的。是否有人为此代码编写了单元测试,或者可以帮助指导我哪里出错以及我是否真的在测试正确的逻辑?

指令:

myApp.directive('csSelect', function () {
    return {
        require: '^stTable',
        template: '',
        scope: {
            row: '=csSelect'
        },
        link: function (scope, element, attr, ctrl) {

            element.bind('change', function (evt) {
                scope.$apply(function () {
                    ctrl.select(scope.row, 'multiple');
                });
            });

            scope.$watch('row.isSelected', function (newValue, oldValue) {
                if (newValue === true) {
                    element.parent().addClass('st-selected');
                } else {
                    element.parent().removeClass('st-selected');
                }
            });
        }
    };
});

单元测试:

 describe('csSelect',function(){
        var scope, element, attr, ctrl;
       beforeEach(module('myApp.selectorresult'));
             beforeEach(inject(function($rootScope, $compile) {
                elm = angular.element(
                    '<td cs-select="row" class="ng-isolate-scope">' +
                    '<input type="checkbox">' +
                    '</td>');
                scope = $rootScope;
                $compile(elm)(scope);
                scope.$digest();
              }));
       it('should create selectable input',function(){
            console.log(elm.find('input'));
            var checkbox = elm.find('input');
            expect(checkbox.length).toBe(1);
      });
    });

【问题讨论】:

    标签: unit-testing angularjs-directive smart-table


    【解决方案1】:

    在设置 beforeEach(inject...

    之前,您需要使用 $controllerProvider 模拟 stTableController

    查看分页指令 (https://github.com/lorenzofox3/Smart-Table/blob/master/test/spec/stPagination.spec.js) 的测试规范,它也需要“stTable”。这是一个很好的例子,说明如何为“stTableController”提供您需要的功能。

    【讨论】:

      【解决方案2】:

      对于仍然遇到此问题的任何人。我希望这有帮助。 我为此苦苦挣扎了很久。我尝试模拟 stTableController,尝试将供应商文件添加到 karma.conf.js 文件中,但无法通过任何测试。 似乎当我删除 require: '^stTable' 时,测试将没有问题通过,但有了它,所有测试都会失败。我无法删除它,因为这会破坏我的代码。

      所以我最终发现,我所要做的就是将 st-table 添加到我在 spec.js 文件中的元素中。

      所以如果我的元素是 var element = angular.element('&lt;my-component&gt;&lt;/my-component'); 我必须成功 var element = angular.element('&lt;my-component st-table&gt;&lt;/my-component&gt;');

      之后,所有测试都通过了。

      【讨论】:

        猜你喜欢
        • 2017-08-23
        • 1970-01-01
        • 1970-01-01
        • 2014-09-21
        • 1970-01-01
        • 2013-05-20
        • 1970-01-01
        • 2014-07-12
        • 2013-06-26
        相关资源
        最近更新 更多