角度指令行为测试Jasmine

时间:2014-10-21 00:09:39

标签: angularjs angularjs-directive angularjs-scope jasmine karma-jasmine

这是Plunker Link

更新了Plunker Updated Plunker

我写了一个隐藏的指令,并根据ajax调用显示div。 我如何测试Directive编写的行为?它显示了Ajax Call上的微调器。

规格

 describe('loader directive', function() {
     var $compile, scope;
     beforeEach(module('plunker'));
     beforeEach(inject(function(_$compile_, _$rootScope_) {
         $compile = _$compile_;
         scope = _$rootScope_.$new();
     }));

     it('check if div shows on', function() {
         var element = $compile('<div loading>Something</div>')(scope);
         scope.$apply();
     });

});

指令

app.directive('loading',   ['$http' ,function ($http)
{
    return {
        restrict: 'A',
        link: function (scope, elm, attrs)
        {
            scope.isLoading = function () {
                return $http.pendingRequests.length > 0;
            };

            scope.$watch(scope.isLoading, function (v) {
                if(v) {
                    elm.show();
                } else {
                    elm.hide();
                }
            });
        }
    };

}]);

1 个答案:

答案 0 :(得分:1)

您只需检查.is(':visible')即可。

describe('loader directive', function() {

  var $compile, scope, $httpBackend, $http, element;

  beforeEach(module('plunker'));

  beforeEach(inject(function(_$compile_, _$rootScope_, _$httpBackend_, _$http_) {
    $compile = _$compile_;
    scope = _$rootScope_.$new();
    $httpBackend = _$httpBackend_;

    $httpBackend.when('GET', '/test').respond(200, {
      test: true
    });

    $http = _$http_;
  }));

  afterEach(function() {
    $httpBackend.flush();

    if (element && element.length) {
      element.remove();
    }
  });

  it('check if div shows on http call', function() {
    element = $compile('<div class="loading-bar" loading>Something</div>')(scope);
    element.appendTo('body');

    $http.get('/test');

    scope.$apply();

    expect(element.is(':visible')).toBe(true);
  });

});

要模拟$http来电,您需要使用$httpBackend服务。

Plunker Demo