Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get scope of custom directive's controller in Jasmine test

I am trying to access scope of the controller attached with **my custom angular directive** when testing in jasmine.

app.directive('MyDirective', function(){
return {
         template:...,
         scope:...,
         controller: function($scope){
                $scope.clickMe = function() {
                    ....
                  };
            $scope.message = "";
         }
 }

I wanna write a test in jasmine to verify if the clickMe method is defined or not.

 it('should have 3 methods', function() {
    expect(dscope).not.toBe(null);
    expect(scope).not.toBe(null);
    expect(angular.isFunction(dscope.clickMe)).toBe(true);
    expect(dscope.message).toBe(true); }

In beforeEach() I declared the scope and dscope variables as follow:

beforeEach(inject(function(  $rootScope, $compile){
    scope = $rootScope.$new();      

    element = angular.element("<div my-directive></div>");

    //bind the empty scope into the directive
    $compile(element)(scope);

    //access to internal directive scope of our element
    dscope = element.scope();  }));

But when I run the test, I get "expect false to be true."* and expect undefined to be not null for scope.message

like image 374
gizmoUb Avatar asked Jun 12 '14 11:06

gizmoUb


1 Answers

If you are using Angular 1.2+, you have to use...

dscope = element.isolateScope();

instead of...

dscope = element.scope();

to access isolated scopes. I can't tell if your scope is isolated because you omitted the scope declaration of your directive in the question, but I'd imagine thats whats happening here.

See this issue on Github for an explanation of the difference between .scope() and .isolateScope()

like image 123
Charlie Martin Avatar answered Oct 26 '22 06:10

Charlie Martin