0

我需要测试一些指令并获取其中一个局部变量来检查其值。该指令本身看起来这样:访问本地变量,同时在AngularJS中进行指令单元测试

angular.module('app').directive('favoritesList', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'templates/directives/favoritesListDirective.html', 
    controller: function ($scope, $rootScope, $rootElement, $filter, ContactService, ContactFollowerService, Restangular) { 

     var listLimit = 100, // in order to prevent favoritesList *overflow* 
      followedFilter = {filters: {followed: true}, page_size:listLimit}; 

     // get Favorites List 
     ContactService.provider.getList(followedFilter) // 
     .then(function(result){ 
      $scope.favorites=result; 
     }, function(message){ 
      console.warn('Cannot get a Favorites List',message); 
     }); 

     .... 


    } 
    }; 
}); 

所以,我怎样才能访问followedFilter变量在描述/它块?

+0

不能的方式,这是写的。请参阅下面的答案 – Katana24

回答

0

我建议打破你的控制器,所以你可以正确抓住它。虽然有可能将控制器从指令中解放出来,但这可能非常困难 - 最简单的做法是让控制器单机运行。例如:

(function() { 
    'use strict'; 

    describe('FavouritesListCtrl', function() { 

    var $rootScope, $scope, ctrl; 
    beforeEach(module('app')); 

    beforeEach(inject(function(_$rootScope_, $controller) { 
     $rootScope = _$rootScope_; 
     $scope  = $rootScope.$new(); 

     ctrl = $controller('FavouritesListCtrl',{$scope: $scope}); 
    })); 

    describe('FavouritesListCtrl', function() { 
     it('should be defined', function() { 
      expect(ctrl).toBeDefined(); 
     }); 
    }); 

    }); 
}); 

在此基础上测试你所期望的控制器去定义,像这样:

(function() { 
    'use strict'; 

    angular 
    .module('app') 
    .component('favoritesList', { 
     bindings: {}, 
     controllerAs: "vm", 
     controller: "FavouritesListCtrl", 
     templateUrl: 'example.html' 
    }); 
}()); 

在这里,我利用组件,而不是指令,但他们很密切相关。如果你想在初始化测试followedFilter,例如:

describe('init', function() { 
    it('followedFilter should be set to ', function() { 
    expect(ctrl.followedFilter).toBeDefined(); 
    }); 
}); 

这会期待followedFilter像这样在控制器中定义:

function FavouritesListCtrl() { 
    var vm = this; 
    vm.followedFilter = { 
    //values 
    }; 
}