Markus Pint
Markus Pint

Reputation: 348

Cannot access isolate scope of directive in Jasmine test

I need to access the isolate scope of a directive in order to test the functions it contains. I have tried all the solutions that I found from SO. The problem is in the isolate scope of the directive, because if I don't set up the directive with isolate scope, the tests work fine.

My directive looks like this:

angular.module('validators').directive('validateName', [function() {

    var directive = {};

    directive.restrict = "A";
    directive.require = 'ngModel';
    directive.scope = {};

    directive.link = function(scope, element, attrs, ngModel) {

        scope.checkIfGoodCharactersOnly = function(name) {

            if ( name.match(/[0-9!$%^&*@#()_+|~=`{}\[\]:";'<>?,.\/]/g) )  {
                return false;
            } else {
                return true;
            }

        };

    };

    return directive;

}]);

The testing set-up looks like this:

beforeEach(module('validators'));

    describe('Directive: validateName', function () {

        var $scope, elem;

        beforeEach(

            inject(function ($compile, $rootScope) {

                $scope = $rootScope.$new();

                elem = angular.element('<form name="form">' +
                '<input name="name" ng-model="transaction.name" validate-name />' +
                '</form>');

                elem = $compile(elem)($scope);

                $scope = elem.isolateScope();

        }));

        describe("Link", function() {

            it("Should call checkIfGoodCharactersOnly", function() {
                 expect($scope.checkIfGoodCharactersOnly("abcd")).toEqual(true);
            });

        });

    });

The output in console:

TypeError: 'undefined' is not an object (evaluating '$scope.checkIfGoodCharactersOnly')

Upvotes: 0

Views: 458

Answers (1)

Markus Pint
Markus Pint

Reputation: 348

Since a form element wraps the input, I was attempting to access the scope of the form element, which does not exist.

This worked:

input = elem.find('input');
expect(input.isolateScope()).toBeDefined();

Upvotes: 1

Related Questions