isolateScope() returning undefined when testing angular directive

谁都会走 提交于 2019-12-23 08:03:15

问题


Using Angular v1.2.25 and rails asset pipeline, I am attempting to test that a directive's isolate scope has indeed been updated. Since isolateScope() returns undefined I am getting expected undefined to be defined ...'

describe("cool directive", function() {

  beforeEach(module('necessaryModule'));

  var scope, $rootScope, $compile, elem,
    baseElement = '<div auto="mock_a" inc="mock_p" method="mock_m" reset-method="mock_r"></div>';

  beforeEach(inject(function( _$rootScope_, _$compile_, _$httpBackend_, $http){
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    angular.extend(scope, {
      mock_a: [
        {name: "example1"},
        {name: "example2"}
      ],  
      mock_m: function(){
        return $http.get('/mockBackend', {
          params:{
            page:  scope.mockPage
          }   
        }); 
      },  
      mock_r: function() {
        scope.page = 1;
        scope.list = []; 
        load();
      },  
      mock_p: 1
    }); 
    $httpListGet = _$httpBackend_;
    $httpListGet.whenPOST('/api/something').respond({});
    $httpListGet.whenGET('/mockBackend').respond({name: "example3"});
    $httpListGet.whenGET('/mockBackend?page=1').respond({name: "example3"});
    $httpListGet.whenGET('/mockBackend?page=2').respond({name: "example4"});
  }));

    var create = function() {
      elem = angular.element(baseElement);
      compiledElement = $compile(elem)(scope);
      elem.scope().$apply();
      return compiledElement;
    };  

  it("has 'list' defined", function() {
    var compiledElem = create();
    var isolateElemScope = compiledElem.isolateScope();
    $rootScope.$apply();
    console.log('isolateElemScope',isolateElemScope);
    expect(isolateElemScope.list).toBeDefined();
  }); 

I'm expecting the directives scope to be accessible and testable, but I'm getting undefined when I test for it. Thank you.


回答1:


to get the isolateScope I use the following code

compiledElem.children().scope()

This is because that most directives don't use replace, which means the directive tag is on the page, and the directive implementation is added as children of that tag. In that case, the isolate scope will belong to the children.

Even if that is not the case, the snippet should still work - as the children will share the parent's scope..

The only case it won't work, is an extreme scenario where you have 2 nested directives, where the inner one uses replace. but I never saw this.




回答2:


Other people coming to this page may have added the test to jasmine but forgotten to add a reference to their directive.



来源:https://stackoverflow.com/questions/27585526/isolatescope-returning-undefined-when-testing-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!