Angularjs单元测试隔离范围值

时间:2015-04-06 15:45:27

标签: angularjs unit-testing jasmine

我的指令看起来像这样:

angular.directive('myDirective', ['$compile', function($compile){
    return {
        link: function(scope, element, attr, controller) {
            function update(){
                if(scope.value == "A"){
                    scope.desc = "Welcome";
                }else{
                    scope.desc = "Not Welcome";
                }
            }

            scope.$watch('value', function(newValue, oldValue) {
                update();
            },true);

            update();
        }
    };
}]);

如何编写可以验证scope.value中的更改的单元测试是否会返回正确的scope.desc

1 个答案:

答案 0 :(得分:2)

基于this question的信息:

// inject $rootScope and $compile in beforeEach
it('should change desc on value change', function() {
  var scope = $rootScope.$new();
  var element = angular.element('<my-directive></my-directive>');
  element = $compile(element)(scope);
  $rootScope.$digest();
  var directiveScope = element.scope();
  expect(directiveScope.desc).toEqual("Not Welcome");
  directiveScope.value = 'A';
  $rootScope.$digest();
  epxect(directiveScope.desc).toEqual("Welcome");
});

Fiddle