测试angularjs指令是否生成HTML代码

时间:2015-09-08 07:09:59

标签: angularjs jasmine

我有一个类似于我想测试的指令,

.directive('gridHeader', function() {
    return {
        restrict: 'A',
        replace: true,
        scope: false,
        compile: function(tEle, tAttrs, transcludeFn) {
            var h3 = tEle.find('h3');
            var temp = h3.html();
            temp = temp.replace('xxxx', tAttrs.gridHeader);
            h3.html(temp);
        },
        template: '<div class="grid-header">' +
            '<h3>Showing {{grid.data.records}} xxxx</h3>' +
            '<div class="pull-right">' +            
            '</div>' +
            '<div class="clearfix"></div>' +
            '</div>'
    }
})

我尝试过类似的东西,但它不起作用

  it('directive: should generate all required html elements', function() {
      var items = angular.element('div.grid-header');    
      console.log(items.length);    //always returning 0
      expect(true).toBe(true);
  });

1 个答案:

答案 0 :(得分:1)

我不喜欢在单元测试中检查指令HTML(我觉得它更适合e2e)但是这样的东西就足够了......

保存对已编译元素的引用

var element;

...

inject(function($rootScope, $compile) {
    var scope = $rootScope.$new();
    scope.grid = { data: { records: 'records' } };

    element = $compile('<div grid-header="foo"></div>')(scope);

    $rootScope.$digest();
});

然后你可以对它进行测试

it('whatever', function() {
    expect(element.hasClass('grid-header')).toBeTruthy();
    expect(element.find('h3').text()).toEqual('Showing records foo');
});