gpt4 book ai didi

angularjs - 用 jasmine 测试 angularjs 指令属性

转载 作者:行者123 更新时间:2023-11-28 21:30:17 24 4
gpt4 key购买 nike

我是 jasmine 测试的新手,遇到了一些问题。我尝试测试这个指令:

指令

myApp.LoadingsDirective = function() {
return {
restrict: 'E',
replace: true,
template: '<div class="loading"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" width="20" height="20" /></div>',
link: function (scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.show);
},
function(val) {
if (val){
$(element).show();
}
else{
$(element).hide();
}
})
}
}
}
myApp.directive('loading', myApp.LoadingsDirective);

这个指令只显示一个加载图标,直到异步请求的结果替换它。

我尝试这样的事情:

测试

describe('Testing directives', function() {
var $scope, $compile, element;

beforeEach(function() {
module('myApp');

inject(function($rootScope, _$compile_) {
$scope = $rootScope.$new();
$compile = _$compile_;
});
});

it('ensures directive show the loading when show attribut is true', function() {
// GIVEN
var element = $compile('<div><loading show="true"> </loading></div>')($scope);
var loadingScope = element.find('loading').scope();

// WHEN
loadingScope.$watch();

// THEN
expect(loadingScope.show).toBe('true');
});
});

测试此类指令的最佳方法是什么?如何访问属性并对其进行测试?

最佳答案

我总是这样做(coffeescript,但你会明白的):

'use strict';

describe 'Directive: yourDirective', ->
beforeEach module('yourApp')

# angular specific stuff
$rootScope = $compile = $scope = undefined
beforeEach inject (_$rootScope_, _$compile_) ->
$rootScope = _$rootScope_
$scope = $rootScope.$new()
$compile = _$compile_

# object specific stuff
element = createElement = undefined
beforeEach inject () ->
createElement = () ->
element = angular.element("<your-directive></your-directive>")
$compile(element)($scope)
$scope.$digest()

it "should have a headline", ->
createElement()
element.find("a").click()
$scope.$apply()
expect(element.find("input").val()).toEqual("foobar")
expect($scope.inputModel).toEqual("foobar")

这可能是指令:

<your-directive>
<a ng-click="spanModel='foobar'">set inputModel</a>
<input ng-model="inputModel">
</your-directive>

首先,我将您创建的元素提取到一个函数中。这允许您在创建指令之前进行一些初始设置。

然后我根据我的指令执行一些操作。如果您想将此操作应用到您的范围(请记住在 jasmine 中您不在 angulars 的摘要圈内),您必须调用 $scope.$apply()$scope.$digest() (现在不记得确切的区别是什么)。

在上面的示例中,您单击了 <a>元素,这有一个 ng-click随附的。这设置了 inputModel范围变量。

未经测试,但您会明白的

关于angularjs - 用 jasmine 测试 angularjs 指令属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24907346/

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