我正在尝试为使用md-select
的指令编写单元测试。我可以定位md-select
元素,但无法访问md-option
元素。
directive.js:
angular.module('myApp')
.directive('myDirective', function ($rootScope) {
return {
restrict: 'A',
scope: {
foo: '=',
},
templateUrl: 'static/partials/my-directive.tmpl.html',
link: function (scope, element, attrs) {
...
scope.options = [
{
name: 'Download', fn: function() {
console.log('download');
},
},
{
name: 'Share', fn: function() {
console.log('share');
},
},
];
}
};
});
directive.tmpl.html:
<md-input-container>
<md-select ng-model="option" placeholder="Options">
<md-option ng-value="opt" ng-click="opt.fn()" ng-repeat="opt in options">{{ opt.name }}</md-option>
</md-select>
</md-input-container>
directive.spec.js
describe('My Directive', function () {
var elm, scope;
beforeEach(module('scriptspeakerApp'));
beforeEach(module('templates'));
beforeEach(inject( function ($rootScope, $compile) {
elm = angular.element(
'<div my-directive foo="script"></div>'
);
$scope = $rootScope.$new();
$scope.foo = 'bar';
elm = $compile(elm)($scope);
$scope.$digest();
}));
it('should have one select element and 2 md-option elements', function () {
var select = elm.find('md-select');
select.triggerHandler("click");
var options = elm.find('md-option');
console.log('options', options);
// output: Object{}
});
我意识到Angular Material
会在页面底部加载md-option
个元素。这是否意味着无法在指令范围内访问选项,而是需要进行e2e测试?
答案 0 :(得分:-1)
问题可能是你的javascript的有效格式,因为有几个应该删除的尾随逗号。您需要将scope.options更改为
scope.options = [
{
name: 'Download', fn: function() {
console.log('download');
} // Removed comma from here
},
{
name: 'Share', fn: function() {
console.log('share');
} // Removed comma from here
} // Removed comma from here
];
我添加了一个测试基于你的指令的示例,我创建了一个关于测试基于md对话框的组件的示例