1

I'm trying to use karma to test AngularJS directives. But I'm running into issues with templateUrls. Using technique described here, it gets even stranger. It seems to work as advertised and loads my template into the $templateCache, but that cache isn't being used by the directive. Here's some code:

This will work just fine

.directive('messageComposer', function($templateCache) {
  return {
    restrict: 'E',
    template: $templateCache.get('partials/message_composer.html'),
    replace: true,
    link: function() {
      console.log('hello world');
    }
  };
});

but as soon as I use a templateUrl, it fails to bind in the tests:

.directive('messageComposer', function() {
  return {
    restrict: 'E',
    templateUrl: 'partials/message_composer.html',
    replace: true,
    link: function() {
      console.log('hello world');
    }
  };
});

Anyone know what's going on here?

Here's my unit test setup:

var $scope;
var $compile;

beforeEach(function() {
    module('partials/message_composer.html');
    module('messageComposer');

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


it("works", function() {
    $scope.message = {};
    elem = angular.element("<message-composer message='message'></message-composer>")
    $compile(elem)($scope);

    console.log(elem);

    expect(true).toBeDefined();
});

1 Answer 1

1

According to the url (http://tylerhenkel.com/how-to-test-directives-that-use-templateurl/), I believe you have run the following command:

npm install karma-ng-html2js-preprocessor --save-dev

Now when you are using the above preprocessor, then this preprocessor will convert HTML files into JS strings and will generate Angular modules. These modules, when loaded, puts these HTML files into the $templateCache and therefore Angular won't try to fetch them from the server.

Hope, the following files will clarify you better:

https://github.com/karma-runner/karma-ng-html2js-preprocessor https://github.com/vojtajina/ng-directive-testing

Sign up to request clarification or add additional context in comments.

2 Comments

That seems to work for the most part, but strangely my directives still don't like the templateUrl. If I use template: $templateCache.get('...'), it works fine tough. Any ideas on what I might be doing wrong?
Do you see GET requests that fail with a 404? Check your basePath setting in your karma config file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.