If this is a unit-test, you won't have access to $httpBackend.passthrough()
. That's only available in ngMock2E2, for end-to-end testing. I agree with the answers involving ng-html2js
(used to be named html2js) but I would like to expand on them to provide a full solution here.
To render your directive, Angular uses $http.get()
to fetch your template from templateUrl
. Because this is unit-testing and angular-mocks
is loaded, angular-mocks
intercepts the call to $http.get()
and give you the Unexpected request: GET
error. You can try to find ways to by pass this, but it's much simpler to just use angular's $templateCache
to preload your templates. This way, $http.get()
won't even be an issue.
That's what the ng-html2js preprocessor do for you. To put it to work, first install it:
$ npm install karma-ng-html2js-preprocessor --save-dev
Then configure it by adding/updating the following fields in your karma.conf.js
{
files: [
//
// all your other files
//
//your htmp templates, assuming they're all under the templates dir
'templates/**/*.html'
],
preprocessors: {
//
// your other preprocessors
//
//
// tell karma to use the ng-html2js preprocessor
"templates/**/*.html": "ng-html2js"
},
ngHtml2JsPreprocessor: {
//
// Make up a module name to contain your templates.
// We will use this name in the jasmine test code.
// For advanced configs, see https://github.com/karma-runner/karma-ng-html2js-preprocessor
moduleName: 'test-templates',
}
}
Finally, in your test code, use the test-templates
module that you've just created. Just add test-templates
to the module call that you typically make in beforeEach
, like this:
beforeEach(module('myapp', 'test-templates'));
It should be smooth sailing from here on out. For a more in depth look at this and other directive testing scenarios, check out this post