单元测试AngularJS(智能表)指令



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

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

指令:

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);
      });
    });

在设置beforeEach(inject…

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

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

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

所以如果我的元素var element = angular.element('<my-component></my-component');我必须去var element = angular.element('<my-component st-table></my-component>');

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

最新更新