Testing controllers that contain $ionicModal.fromTemplateUrl()


#1

My controller has the following code:

$ionicModal.fromTemplateUrl('views/Dialog.html', { 
    scope: $scope 
}).then(function (modal) { 
    $scope.modal = modal; 
});

It works fine when I run the app. But, when I run my Jasmine test script using Karma, before it even has a chance to run any tests, I get the following error:

Error: Unexpected request: GET views/Dialog.html

When I comment out the above lines of code, the tests run fine. I understand why the error is being raised… because Jasmine knows nothing about Dialog.html. But, my question is, does Ionic/Angular provide a way to make it believe that the template URL has been loaded? This seems to be a general problem with unit testing anytime external HTML is loaded dynamically from within controller code.


#2

Use the following

    $httpBackend = $injector.get('$httpBackend');
    $httpBackend.when('GET', 'views/Dialog.html').respond('');

#3

I have written many tests and had to include something similar to what you suggested several times. Is there a way to avoid this? I got many templates and files so it’s not that convenient.


#4

Just had the same issue and then checked the docs of “when” here:
https://docs.angularjs.org/api/ngMock/service/$httpBackend

The great thing is that the “url” parameter can also be a regex. So if you simply write:

$httpBackend.when('GET', /.*/).respond('');

It will match everything and you do not have to write a “when” for each file.


#5

There is a better way to deal with templates used in tests.

This karma plugin “precompiles” templates as angular inline templates. Then karma/jasmine do not have to load the templates in the process of testing. They will be just there.