使用ng-html2js进行AngularJS指令测试

时间:2014-09-08 13:54:05

标签: javascript angularjs unit-testing ng-html2js

关于ng-html2js插件有很多问题,但不幸的是,所有答案并没有帮助我解决问题。

我按照官方安装指南和示例https://github.com/vojtajina/ng-directive-testing/blob/master/test/tabsSpec.js

我的目标是测试一个具有templateUrl属性的指令,这是我的配置

karma.conf.js

files: [
  ... // lots of studd here

  'app/views/**/*.html' // templates are all here
],

[...] // other karma configs here

preprocessors: {
  'app/views/**/*.html': ['ng-html2js']
},

我想测试它的指令是非常基本的

'use strict';

angular.module('myAwesomeApp').directive('rzMenu', function () {
    return {
      templateUrl: 'views/directives/rzmenu.html',
      restrict: 'E'
    };   
});

的单元测试文件
'use strict';

describe('Directive: rzmenu', function () {

  // load the directive's module
  beforeEach(module('myAwesomeApp'));
  beforeEach(module('app/views/directives/rzmenu.html'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope, $compile) {
    element = angular.element('<rzmenu></rzmenu>');
    scope = $rootScope.$new();
    element = $compile(element)(scope);
    scope.$digest();
  }));

  it('should have content', inject(function () {
    //scope.$digest();
    var content = element.text();
    expect(content).toBe('');
  }));
});

看看&#39;应该有内容&#39;测试,不应该是与模板相同的内容吗?

为什么我得到并清空字符串?

提前致谢

1 个答案:

答案 0 :(得分:4)

没关系, 我解决了2个错误:

1)cacheIds必须匹配templateUrl属性,所以

stripPrefix: 'app/'
配置中需要

以及在测试中没有app /前缀的情况下调用模块。

beforeEach(module('views/directives/rzmenu.html'));

2)指令名称为camelCase,因此实例调用错误,下面是正确的

element = angular.element('<rz-menu></rz-menu>');

:)