我见过类似的问题,但没有一个解决问题的根源,假设如下:
- 我不能使用
whenGET('').passThrough()
,因为我没有使用ngMockE2E - 我不应该使用ngMockE2E,因为我正在为一个指令写一个单元测试,这个指令除了吐出"bar"之外什么都不做
- 一个建议是使用代理服务器来提供这些HTTP响应,但这不是违背了单元测试的目的吗
现在,让我向您展示我的指令:
angular.module('app')
.directive('foo', function () {
return {
restrict: 'A',
templateUrl: 'templates/bar.html'
};
});
这是单元测试:
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
}));
});
现在,测试可以很好地处理所有这些伪造的$httpBackend
业务,但这完全不属于我的单元测试!我该如何摆脱$httpBackend
的垃圾,并阻止AngularJS应用程序配置块在我的指令单元测试中使用templateUrl运行?
注意:只有当指令中存在templateUrl时才会发生这种情况
顺便说一句,在应用配置块中触发此HTTP请求的代码是:
$translatePartialLoaderProvider.addPart('index');
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/translations/{part}/{lang}.json'
});
但我认为这并不一定相关。
将指令放入它们自己的模块中,并将该模块包含在主应用程序模块中。然后,您可以在不加载应用程序模块的情况下测试指令模块。
例如
angular.module('app-directives', [])
.directive('foo', function () {
return {
restrict: 'A',
templateUrl: 'templates/bar.html'
};
});
angular.module('app', ['app-directives'])
//Run your config stuff here