Ila*_*sda 8 tdd jasmine angularjs angularjs-directive karma-jasmine
我有一个像这样的AngularJS指令示例 <div some-dir="5" />
如何5在我的测试中访问此指令属性值?
describe("some-dir", function() {
var element, scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope;
element = angular.element('<div><div id="el1" some-dir="5" /></div>');
$compile(element)(scope);
scope.$digest();
}));
it('should be able to get the attribute value', function(){
// get the attr value of some-dir
});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用其isolateScope方法检查元素的范围值.但是,当您在指令属性旁边传递值时,这将不起作用,因为这些值不会复制到隔离范围中.
在这种情况下,可以使用element.attributes方法获取并测试该值.
首先编译你的指令html:
var element;
beforeEach(inject(function (_$compile_, _$rootScope_) {
var $compile = _$compile_,
$scope = _$rootScope_;
element = $compile('<div my-directive="4" some-value="5"></div>')($scope);
$scope.$digest();
}));
Run Code Online (Sandbox Code Playgroud)
然后你可以期望element的isolateScope返回一个带有someValue属性的对象.
it('should expect some-value as 5', function () {
inject(function ($injector) {
// check attribute values using isolateScope
expect(element.isolateScope().someValue).toEqual(5);
// check the value right after directive attribute
expect(element.attr('my-directive')).toEqual('4');
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个示例的plunker.
| 归档时间: |
|
| 查看次数: |
14755 次 |
| 最近记录: |