I've seen similar questions asked, but not one of them resolves the root of the problem, which assumes the following:
- I can't use
whenGET('').passThrough()
, because I'm not using ngMockE2E. - I shouldn't need to use ngMockE2E because I'm writing a unit test for a directive that literally does nothing but spit out "bar".
- One suggestion was to use a proxy server to serve-up these HTTP responses, but doesn't that defeat the purpose of a unit test?
Now, let me show you my directive:
angular.module('app')
.directive('foo', function () {
return {
restrict: 'A',
templateUrl: 'templates/bar.html'
};
});
And here is the unit test:
describe('Directive: foo', function () {
// load the directive's module
beforeEach(module('app'));
var $compile;
var $rootScope;
var $httpBackend;
beforeEach(inject(function(_$compile_, _$rootScope_, $injector) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$httpBackend = $injector.get('$httpBackend');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should be bar', inject(function($templateCache) {
$templateCache.put('templates/bar.html', 'bar');
var element = $compile('<div data-foo></div>')($rootScope);
//$httpBackend.whenGET(/^\/translations\//).passThrough(); // doesn't work
$httpBackend.expectGET(/\/translations\//).respond('201', ''); // works
$rootScope.$digest();
$httpBackend.flush();
expect(element.text()).toBe('bar'); // works
}));
});
Now, the test works just fine with all this bogus $httpBackend
business in there, but this totally doesn't belong in my unit tests! How do I pull this $httpBackend
crap out and stop the AngularJS app config blocks from running in my directive unit tests with a templateUrl?
Note: This only happens when there is a templateUrl in the directive.
BTW, the code that's triggering this HTTP request in the app config block is:
$translatePartialLoaderProvider.addPart('index');
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/translations/{part}/{lang}.json'
});
But I don't think that's necessarily relevant.