新的角度.js并且无法弄清楚如何使用templateUrl和隔离范围为指令编写测试。
这是我的控制器
(function(){
angular.module('buttons')
.controller('buttonController', ['$scope', function($scope){
//primary button
$scope.primaryButton = { name: 'Submit'};
})();
这是我的观点索引.html &
<div class="layoutLeft">
<p>Primary Button</p>
<primary-button info="primaryButton"></primary-button>
</div>
主按钮.html
<button class="{{buttonInfo.class}}">{{buttonInfo.name}}</button>
这是我的指示
(function(){
angular.module('buttons')
.directive('primaryButton', function() {
return {
restrict: 'EA',
scope: {
buttonInfo: '=info'
},
templateUrl: 'scripts/local/views/primary-button.html'
}
})
})();
这是我的测试
(function(){
beforeEach(angular.mock.module('buttons'));
describe('Buttons Directive Test', function(){
var $compile, $scope, $httpBackend;
beforeEach(module('templates'));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
$scope.primaryButton = {name: 'Save'};
elm = angular.element("<primary-button info='buttonInfo'></primary-button>");
e = $compile(elm)($scope);
e.digest();
}));
it('should do something', function(){
expect(e.html()).toContain($scope.primaryButton);
});
});
})();
我正在使用茉莉花和业力进行测试,有人可以指导我做错了什么
编辑:这是一个 plunkr,演示了非常接近您的代码正在做的事情。您的问题中的代码存在多个问题,我已经修复了:
http://plnkr.co/edit/QXprEUof2Ps0Vivg4L34?p=preview
- 在您的测试中,您调用 e.digest(),这将不起作用,因为您无法消化元素...您应该改为调用 $scope.$digest。
- e.html() 将不包含该 JSON blob。我将其解释为希望它包含名称标签...
- info='buttonInfo' 将 info 绑定到外范围中的属性 buttonInfo,但您将其称为"primaryButton"。将 $scope.primaryButton 重命名为 $scope.buttonInfo
- 你使用了一些不完全必要的下划线,但这没什么大不了的,在注入编译时,rootscope
- 我使用了一个内联模板,而不是仅为 plunkr 加载它,加载它没有错
- 因为你的指令是一个元素,所以我添加了"替换",它用一个直按钮替换了元素。请考虑将其设为属性。
我的 plunkr 通过了茉莉花测试和按钮的工作演示。如果您需要更多帮助,请告诉我。祝AngularJS好运。
(旧答案)
====
==========您将需要使用类似nghtml2js的东西来加载模板并使它们可用于模板缓存。
使用 nghtml2js
这是你的第一个问题。第二个问题是通过在编译元素后对元素调用 isolateScope() 来完成隔离范围。在 elem 上记录调用它的结果,您将找到所需的属性。
e.isolateScope()
不遵循为什么上述答案被标记为已接受。 该问题询问如何使用 templateUrl 完成,而@PeterAshwell的答案提供了一种使用内联 HTML 的解决方案,该解决方案在使用 templateURL 时不起作用。
若要在使用 templateUrl 时获得对隔离作用域的访问权限,必须将 isolateScope 调用包装在$timeout中,以允许$http调用(由 templateUrl 进行)完成。
代码将如下所示:
element = $compile("<myHTML />")($scope)
$timeout(function() {
expect(element.isolateScope().myProp).toEqual(12);
}), 0 , false);
$timeout.flush();