gpt4 book ai didi

angularjs - 无法使用 mocha 测试指令范围

转载 作者:行者123 更新时间:2023-12-01 01:48:41 27 4
gpt4 key购买 nike

我有一个带有独立范围的简单指令,我正在尝试测试它。问题是我无法测试 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;
});
});

根据我一直在网上阅读的内容,这应该有效。因此,经过数小时的研究>失败>重复,我倾向于认为这是我的源代码版本的错误或问题。有什么想法吗?

注意 我正在使用 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 .

最佳答案

对于和我有同样问题的人,下面是解决方案。

MOCHA 中,如果您为指令使用外部 html 模板,则必须使用 ng-html2js preprocessor这会将您的所有模板缓存在一个 js 文件中。完成此设置后,karma 将读取这些而不是尝试获取实际的 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

关于angularjs - 无法使用 mocha 测试指令范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25922937/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com