1

I know you can load, compile and test an Angular directive something like so:

it('Replaces the element with the appropriate content', function () {

    var element = $compile("<my-directive></my-directive>")($rootScope);
    $rootScope.$digest();

    expect(element).toContain("some HTML...");
});

Is there a way to do exactly the same but loading and compiling an HTML fragment (from a file) instead of having to create a directive? The fragment is just an ngRepeat and an ngController - wrapping this into a directive is just an added layer of unnecessary complexity, but I'd still like to be able to test the generated HTML.

For example, for an HTML partial `my-table.html':

<table class="table table-condensed table-striped" data-ng-controller="MyController">
 <tbody>
    <tr data-ng-repeat="item in myItems">
...

I'd have a Jasmine test that looked something like:

it('Replaces the element with the appropriate content', function () {

    var element = $compile("my-table.html")($rootScope);
    $rootScope.$digest();

    expect(element).toContain("some HTML...");
});
glasswall
  • 127
  • 1
  • 10
  • You can try with the stackoverflow link http://stackoverflow.com/questions/27026596/accessing-compiled-template-in-unit-tests – isc Oct 25 '16 at 09:31

1 Answers1

1

I don't think you should test only the template of directive, because directive is what is used in your code, not template by itself.

However, I imagine you should do $http.get('my-table.html'), get the contents into variable and compile that.

Edit:

Here is some code:

var template;

beforeEach(inject(function($http, $httpBackend){
    $http.get('my-table.html').then(function(data) {
        template = data;
    });

    $httpBackend.flush();
}));

it('Replaces the element with the appropriate content', function () {

    var element = $compile(template)($rootScope);
    $rootScope.$digest();

    expect(element).toContain("some HTML...");
});

This is just an idea how it should work. Not sure if this actually works - haven't tested it, but this is how I would do it if I would need that.

domakas
  • 1,246
  • 8
  • 9
  • Yeah I get that, but if all you have is a controller and a repeater, why bother wrapping that up into a directive? It just doesn't add any value - I just want to ensure the HTML generated in my partial is OK - does that make sense? – glasswall Jul 29 '14 at 15:16
  • What do you mean by `$http.get` - is this an angular service? Can you give me a code example? thanks – glasswall Jul 29 '14 at 15:38