Test angular directive with templateUrl

2k views Asked by At

I am trying to test my Angular directive with Karma+Jasmine. So as my directive has templateUrl I need caching the template with karma-ng-html2js-preprocessor. My karma.conf.js file:

...
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'
}
...

And my jasmine spec:

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

});

But seems that for some reasons it cannot inject my templates module: TypeError: undefined is not a function (evaluating '$compile(.... How to correctly get those things work together?

1

There are 1 answers

0
Most Wanted On

So, the problem was solved with altering the configuration

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

and preprocessor is actually without the leading slash

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

So, actually in your directive the path to the template should be exactly like this /statics/views/directives/my-directive.html. And the other thing: do not forget to include $scope.$digest(); to directive to be rendered with all the context.