I have a example AngularJS directive like this <div some-dir="5" />
How would I access this directive attribute value of 5
inside my test?
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
});
});
You can check scope values of element using its isolateScope method. But this won't work when you pass a value right next to directive attribute, as those values are not copied into isolated scope.
In that case, it's possible to get and test that value using element.attributes method.
First compile your directive 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();
}));
Then you can expect element's isolateScope to return an object with someValue property.
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');
});
});
Here is an example plunker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With