Angular Karma - 具有隔离范围和控制器的指令,调用element.isolateScope()返回undefined

时间:2016-04-14 21:03:39

标签: angularjs testing karma-jasmine isolate-scope

你有这个指令:

angular.module('xos.uiComponents.table', [])
.directive('xosTable', function(){
  return {
    restrict: 'E',
    scope: {
      data: '=',
      config: '='
    },
    template: `
      <!-- <pre>{{vm.data | json}}</pre> -->
      <table ng-class="vm.classes" ng-show="vm.data.length > 0">
        <thead>
          <tr>
            <th ng-repeat="col in vm.columns">{{col.label}}</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="item in vm.data">
            <td ng-repeat="col in vm.columns">{{item[col.prop]}}</td>
          </tr>
        </tbody>
      </table>
    `,
    bindToController: true,
    controllerAs: 'vm',
    controller: function(){

      if(!this.config){
        throw new Error('[xosTable] Please provide a configuration via the "config" attribute');
      }

      if(!this.config.columns){
        throw new Error('[xosTable] Please provide a columns list in the configuration');
      }

      this.columns = this.config.columns;
      this.classes = this.config.classes || 'table table-striped table-bordered';

    }
  }
})

我正在尝试测试但我无法访问isolateScope(),这是我的测试代码:

describe('when correctly configured', function() {
  let scope, element, is;

  beforeEach(inject(function ($compile, $rootScope) {
    scope = $rootScope.$new();

    scope.config = {
      columns: [
        {
          label: 'Label 1',
          prop: 'label-1'
        },
        {
          label: 'Label 2',
          prop: 'label-2'
        }
      ]
    };

    scope.data = [
      {
        'label-1': 'Sample 1.1',
        'label-2': 'Sample 1.2'
      },
      {
        'label-1': 'Sample 2.1',
        'label-2': 'Sample 2.2'
      }
    ]

    element = angular.element('<xos-table config="config" data="data"></xos-table>');
    $compile(element)(scope);
    is = element.isolateScope();
    scope.$digest();

  }));

  it('should contain 2 columns', function() {
    expect(is.columns).toEqual(2);
  });
});

我有很多次这样的设置,任何关于为什么我无法访问我的指令的isolateScope的想法?

这是一个包含代码和测试的Plunker:http://plnkr.co/edit/JYYtck?p=preview

1 个答案:

答案 0 :(得分:1)

你在测试中犯了三个错误:

  1. 您没有加载包含该指令的模块(它在一个单独的describe块中加载)。这就是isolateScope未定义的原因;
  2. 您使用scope.columns代替os scope.vm.columns;
  3. 您将columns数组与2进行比较,而不是将其长度与2进行比较。
  4. 这是fixed plunkr

    提取物:

    beforeEach(module('xos.uiComponents.table'));
    
    [...]
    
    it('should contain 2 columns', function() {
        console.log('aaa', iso);
    
        // one is the filter, the other two are the products, one is the pagination
        expect(iso.vm.columns.length).toEqual(2);
    });