使用templateUrl测试角度指令

时间:2016-04-27 22:36:25

标签: angularjs angularjs-directive karma-runner karma-jasmine ng-html2js

我正试图用Karma + Jasmine测试我的Angular指令。因此,我的指令有templateUrl,我需要使用karma-ng-html2js-preprocessor缓存模板。 我的 karma.conf.js 文件:

...
files: [
  ...
  'static/views/**/*.html', // to match my directive template
  ...
],

preprocessors: {
  '/static/views/**/*.html': ['ng-html2js]  // to catch the filename as specified in templateUrl 
},

ngHtml2JsPreprocessor: {
  moduleName: 'templates'
}
...

我的茉莉花规格:

describe('Directive unittesting', function() {
  beforeEach(module('myModule'));
  beforeEach(module('templates'));

  var $compile, $scope;

  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $scope = _$rootScope_.$new();
  }));

  it('Replaces the element with the appropriate content', function() {
    var element = $compile("<my-directive></my-directive>")($scope);
    expect(element.html()).toContain("text to contain");
  });

});

但似乎由于某些原因它无法注入我的templates模块:TypeError: undefined is not a function (evaluating '$compile(...。如何正确地让这些东西一起工作?

1 个答案:

答案 0 :(得分:2)

因此,通过更改配置解决了问题

ngHtml2JsPreprocessor: {
  prependPrefix: '/',
  moduleName: 'templates'
},

和预处理器实际上没有前导斜杠

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

因此,实际上在您的指令中,模板的路径应该与此/statics/views/directives/my-directive.html完全相同。 另一件事:不要忘记将$scope.$digest();包含在指令中以便用所有上下文进行渲染。

相关问题