Reputation: 174
I do NOT want to use karma-ng-html2js-preprocessor or $httpBackend. I have a templateCache module which I created dynamically.
app.js
angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ui.router', 'appTemplates']);
templates.js
(function(){
'use strict';
angular.module('appTemplates', []).run(['$templateCache',
function($templateCache) {
$templateCache.put('js/Templates/datetimepicker.html', '<div>My html here</div>');
}
]);
})();
And a directive
datetimepicker.js
angular.module('myApp').directive('datetimepicker',
function () {
return {
restrict: 'A',
replace: false,
templateUrl: 'js/Templates/datetimepicker.html'
};
}
);
The problem is, my test does not seem to want to use the templateCache when I compile a directive.
test.js
(function () {
"use strict";
describe("Datetimepicker directive tests", function () {
var scope, templateCache, element;
// load the directive's module
beforeEach(module('myApp'));
beforeEach(inject(function ($rootScope, $templateCache) {
scope = $rootScope;
templateCache = $templateCache;
}));
it('should exist', inject(function ($compile) {
//this console.log prints out the correct HTML from cache
//console.log(templateCache.get('js/Templates/datetimepicker.html'));
element = angular.element('<div data-datetimepicker></div>');
element = $compile(element)(scope);
// this logs the element
console.log(element);
//this $digest call throws the error
scope.$digest();
console.log(element);
expect(element.html()).toContain('div');
}));
});
})();
I get:
Error: Unexpected request: GET template/datepicker/datepicker.html
No more request expected at $httpBackend in my console when I run the test.
Any help appreciated. Thanks
Upvotes: 2
Views: 1844
Reputation: 174
The clue was in the error. The datetimepicker directive contains an Angular-UI directive called datepicker. It is this that is causing the error. I guess my directive is not unit testable, and I will focus on E2E tests for this one. The question is therefore misleading, as the template actually contained more HTML than I posted here. Thanks anyway, SO! Hopefully this answer will help people who are getting the same error though!
Upvotes: 0
Reputation: 31202
Either directive module should reference the template cache module as a dependency :
angular.module('myApp', ['appTemplates']).directive('datetimepicker',
Or load the module manually in your test :
// load the directive's module
beforeEach(module('myApp'));
beforeEach(module('appTemplates'));
Otherwise the template cache module run
method would not execute, and as such, no templates in cache.
Upvotes: 2
Reputation: 5417
Use the $httpBackend mock service, for requests.
//expect a GET request to a url.
$httpBackend.expectGET('whatever url you want');
//...place your code.
//flush pending requests.
$httpBackend.flush();
For more information see the official angular $httpBackend service page.
Upvotes: 0