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 {
         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.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

    //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

Problem courtesy of: gizmoUb


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()

Solution courtesy of: Charlie Martin


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.