我有一个简单的指令,我正在尝试测试一个隔离的范围。问题是我无法测试link
函数中定义的范围变量。以下是我的指令和规范的淡化样本。
指令:
angular.module('myApp').directive('myDirective', [function(){
return {
scope: {},
restrict: 'AE',
replace: 'true',
templateUrl: 'template.html',
link: function link(scope, element, attrs){
scope.screens = [
'Screen_1.jpg',
'Screen_2.jpg',
'Screen_3.jpg',
];
}
};
}]);
规格
describe.only('myDirective', function(){
var $scope, $compile;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$compile_, $httpBackend){
$scope = _$rootScope_.$new();
$compile = _$compile_;
$httpBackend.when('GET', 'template.html').respond();
}));
function create(html) {
var elem, compiledElem;
elem = angular.element(html);
compiledElem = $compile(elem)($scope);
$scope.$digest();
return compiledElem;
};
it('should have an isolated scope', function(){
var element = create('<my-directive></my-directive>');
expect(element.isolateScope()).to.be.exist;
});
});
根据我在线阅读的内容,这应该有效。因此,经过数小时的研究&gt;失败&gt;重复我倾向于认为这是我的源代码版本的错误或问题。有什么想法吗?
注意我正在使用Angular 1.2.17
,jQuery 1.11.0
,Karma ~0.8.3
和最新Mocha
更新9月19日
我更新了上面的指令,为简单起见,我写了一个内联模板,但我的实际代码有一个外部templateUrl
。我还在测试中添加了$httpBackend.when()
以防止测试实际上尝试获取html文件。
我注意到内联模板使一切正常,但是当我使用外部模板时,它不会触发link
函数。
更新9月19日
我集成了html2js
,现在我能够从缓存中加载模板并触发link
功能。很遗憾,isolateScope()
仍然出现undefined
。
答案 0 :(得分:2)
对于与我有同样问题的人,以下是解决方案。
在 MOCHA 中,如果您为指令使用外部html模板,则必须使用ng-html2js preprocessor来缓存js文件中的所有模板。一旦你有了这个设置,业力将会读取这些而不是试图获取实际的html文件(这将阻止UNEXPECTED REQUEST: GET(somepath.html)
错误。)
正确设置后。您可以通过link
将指令controller
功能或isolateScope()
范围用于您的测试。以下是更新后的代码:
describe('myDirective', function(){
var $scope, $compile;
beforeEach(module('myApp'));
beforeEach(module('ngMockE2E')); // You need to declare the ngMockE2E module
beforeEach(module('templates')); // This is the moduleName you define in the karma.conf.js for ngHtml2JsPreprocessor
beforeEach(inject(function(_$rootScope_, _$compile_){
$scope = _$rootScope_.$new();
$compile = _$compile_;
}));
function create(html) {
var compiledElem,
elem = angular.element(html);
compiledElem = $compile(elem)($scope);
$scope.$digest();
return compiledElem;
};
it('should have an isolated scope', function(){
var elm = create('<my-directive></my-directive>');
expect(elm.isolateScope()).to.be.defined;
});
});
注意我遇到了问题,在我认为我已正确设置所有内容后仍然出现UNEXPECTED REQUEST: GET...
错误,结果发现我的缓存文件的路径与请求实际文件,请查看此帖子以获取更多帮助:
Karma 'Unexpected Request' when testing angular directive, even with ng-html2js