gpt4 book ai didi

angularjs - 如何在指令中对隔离范围进行单元测试

转载 作者:行者123 更新时间:2023-12-02 19:18:28 26 4
gpt4 key购买 nike

我正在尝试对一个简单的指令进行单元测试,但作用域中的变量始终未定义。

指令源代码:

.directive('ratingButton', ['$rootScope',


function($rootScope) {
return {
restrict: "E",
replace: true,
template: '<button type="button" class="btn btn-circle" ng-class="getRatingClass()"></button>',
scope: {
buttonRating: "="
},
link: function(scope, elem, attr) {
scope.getRatingClass = function() {
if (!scope.buttonRating)
return '';
else if (scope.buttonRating.toUpperCase() === 'GREEN')
return 'btn-success';
else if (scope.buttonRating.toUpperCase() === 'YELLOW')
return 'btn-warning warning-text';
else if (scope.buttonRating.toUpperCase() === 'RED')
return 'btn-danger';
else if (scope.buttonRating.toUpperCase() === 'BLUE')
return 'btn-info';
}
}
};
}])

测试:

describe('Form Directive: ratingButton', function() {

// load the controller's module
beforeEach(module('dashboardApp'));

var scope,
element;

// Initialize the controller and a mock scope
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope.$new();

//set our view html.
element = angular.element('<rating-button button-rating="green"></rating-button>');
$compile(element)(scope);
scope.$digest();
}));

it('should return appropriate class based on rating', function() {
//console.log(element.isolateScope());
expect(element.isolateScope().buttonRating).toBe('green');
expect(element.isolateScope().getRatingClass()).toBe('btn-success');

});

});

我在另一个指令单元测试中使用了类似的代码,通过元素属性传递值,并且它按预期工作。对于此测试,按钮评级始终未定义,不确定从这里该去哪里(我对 Jasmine/Karma 还很陌生)

任何帮助都会很棒!

最佳答案

而不是设置字符串 green在测试启动时编译指令元素时,将其设置在范围边界上。否则,它将查找名称为 green 的范围属性的值。在绑定(bind)范围上,当然在您的情况下没有定义。

scope.buttonRating = 'green';

angular.element('<rating-button button-rating="buttonRating"></rating-button>')

尝试:

  // Initialize the controller and a mock scope
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope.$new();
scope.buttonRating = 'green'; //<-- Here
//set our view html.
element = angular.element('<rating-button button-rating="buttonRating"></rating-button>');
$compile(element)(scope);
scope.$digest();
}));

it('should return appropriate class based on rating', function() {
expect(element.isolateScope().buttonRating).toBe('green');
expect(element.isolateScope().getRatingClass()).toBe('btn-success');

});

<强> Plnkr

关于angularjs - 如何在指令中对隔离范围进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894305/

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