Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access directive attribute value in the jasmine test

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


    });

});
like image 790
Iladarsda Avatar asked Nov 19 '14 13:11

Iladarsda


1 Answers

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.

like image 175
halilb Avatar answered Oct 20 '22 13:10

halilb