Words Like Jared Words Like Jared - 2 months ago 7
AngularJS Question

Unit Testing AngularJS directive with templateUrl

I have an AngularJS directive that has a

templateUrl
defined. I am trying to unit test it with Jasmine.

My Jasmine JavaScript looks like the following, per the recommendation of this:

describe('module: my.module', function () {
beforeEach(module('my.module'));

describe('my-directive directive', function () {
var scope, $compile;
beforeEach(inject(function (_$rootScope_, _$compile_, $injector) {
scope = _$rootScope_;
$compile = _$compile_;
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET('path/to/template.html').passThrough();
}));

describe('test', function () {
var element;
beforeEach(function () {
element = $compile(
'<my-directive></my-directive>')(scope);
angular.element(document.body).append(element);
});

afterEach(function () {
element.remove();
});

it('test', function () {
expect(element.html()).toBe('asdf');
});

});
});
});


When I run this in my Jasmine spec error I get the following error:

TypeError: Object #<Object> has no method 'passThrough'


All I want is for the templateUrl to be loaded as is - I don't want to use
respond
. I believe this may be related to it using ngMock instead of ngMockE2E. If this is the culprit, how do I use the latter instead of the former?

Thanks in advance!

Answer

What I ended up doing was getting the template cache and putting the view in there. I don't have control over not using ngMock, it turns out:

beforeEach(inject(function(_$rootScope_, _$compile_, $templateCache) {
    $scope = _$rootScope_;
    $compile = _$compile_;
    $templateCache.put('path/to/template.html', '<div>Here goes the template</div>');
}));