Brian Colwell
Brian Colwell

Reputation: 79

Using $templateCache to compile a custom directive in a jasmine test

I am new to Angular and asking for help here so please bear with me.

I am trying to test a custom directive that uses a templateUrl. I am using Jasmine, Grunt, and the html2js Grunt plugin. I do not want to mock http request/response or use Karma.

My goal is to preload the template cache before my test and have angular resolve the directive html from the cache. I have extracted the js template from the file created by html2js to simplify my test temporarily. I cannot figure out why $compile does not inject the template into my test html. Here is my code:

beforeEach(inject(function($rootScope, $controller, $compile, $templateCache) {
    isolatedScope = $rootScope.$new();
    testCtrl = $controller('valueGaugeCtrl', {
        $scope: isolatedScope
    });
    $templateCache.put("App/Common/Widgets/ValueGauge.html",
  "<div ng-controller=\"valueGaugeCtrl\">\n" +
  " <div class=\"valueGauge\">\n" +
  "     <h4>{{gaugetype}}:</h4>\n" +
  "     <h2>{{technique[gaugetype]}}</h2>\n" +
  "     <div>\n" +
  "         <button ng-click=\"onPlusClick()\" class=\"btn-default glyphicon glyphicon-plus plusMinusButton\"></button>\n" +
  "         <button ng-click=\"onMinusClick()\" class=\"btn-default glyphicon glyphicon-minus plusMinusButton\"></button>\n" +
  "     </div>\n" +
  " </div>\n" +
  "</div>");
    html = '<value-gauge gaugetype="someType"></value-gauge>';
    vg = angular.element(html);
    linkFn = $compile(vg);

At this point I would expect vg to have been injected with my template html. Instead, only 'class="ng-isolate-scope ng-scope' has been injected into the original vg.

If I specify the template html inline in the custom directive (rather than using templateUrl), the $compile works as expected and injects the html into vg.

Thanks very much in advance.

Upvotes: 2

Views: 2913

Answers (1)

Jeff Whelpley
Jeff Whelpley

Reputation: 579

Unless you are testing a part of your code that does some dynamic compilation, you should not do this in your test code. Assuming you are simply referencing some remote template, one option would be to use Grunt with the grunt html2js plugin to convert your templates into a JS package that you can inject into your test code.

Upvotes: 1

Related Questions