测试element.bind('错误')

时间:2016-05-30 16:34:56

标签: javascript angularjs unit-testing

试图弄清楚如何测试这个指令,但是当我退出element时,我只是继续这样做。

Object{0: <img ng-src="img/img.jpg" err-src="img/err.png" src="img/img.jpg">, length: 1}

我如何使用不同的http代码对此进行测试,以确保我的指令正常工作?

directive.js

.directive('errSrc', function() {
  return {
    link: function(scope, element, attrs) {

      scope.$watch(function() {
        return attrs.ngSrc;
      }, function (value) {
        if (!value) {
          element.attr('src', attrs.errSrc);
        }
      });

      element.bind('error', function() {
        element.attr('src', attrs.errSrc);
      });
    }
  };
})

test.js

describe("Directives", function () {


    describe("err-src Directive", function () {


        var element, $scope;
        beforeEach(module('app'));

        beforeEach(inject(function ($compile, _$rootScope_, _$httpBackend_) {

            $scope = _$rootScope_.$new();
            $httpBackend = _$httpBackend_;

            element = angular.element('<img ng-src="img/img.jpg" err-src="img/err.png">');

            element = $compile(element)($scope);

            $scope.$digest();
            console.log(element);

        }));

        it("Should replace src with err icon if 404", function () {
            $httpBackend
                    .when('GET', 'img/img.jpg')
                    .respond(404);
        });
        it("Should replace src ng-src if 200", function () {
            $httpBackend
                    .when('GET', 'img/img.jpg')
                    .respond(200);


        });
    });
});

0 个答案:

没有答案