在范围内找不到角度指令功能

时间:2015-09-08 16:00:27

标签: angularjs unit-testing

我需要为一个angular指令编写一个测试但是我收到错误:Error:removeItem()方法不存在。我一直试图解决这个问题,直到头疼,如果有人能指出什么是错的,那将非常感激。

指令

angular.module('app')
.directive('cartItem', function () {
    return {
        template: '<div class="cartItem"><div class="pull-left">' +
        '<p class="pull-left">{{ cartItem.brand_name }}' +
        '<a class="cartRemove" ng-click="removeItem(cartItem)">&nbsp;{{removeItemLabel}}</a>' +
        '</p></div><p class="cartItemPrice pull-right">{{ cartItem.priceUnformatted }} {{symbol}}</p></div>'
        },
        link: function postLink(scope) {
            scope.removeItem = function(entity){
                scope.removeItemFromCart(entity);
            };
        }
    };
});

和我的测试

describe('', function(){
var element, scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $compile) {

    element = angular.element(
        '<div cart-item ' +
        'remove-item-from-cart="removeItemFromCart(item)"' +
        'attr-locale="\'EN\'" ' +
        'attr-remove-item-label="\'Remove item\'"' +
        'attr-formatted="true"' +
        'attr-cart-item=""></div>');

    scope = $rootScope.$new();
    $compile(element)(scope);
    scope.$digest();
}));

it('should call remove on click', function(){
    spyOn(scope, 'removeItem');
    element.click();
    expect(scope.removeItem).toHaveBeenCalled();
});

});

removeItem会抛出错误消息错误:removeItem()方法不存在。

2 个答案:

答案 0 :(得分:0)

尝试使用以下代码更改指令代码:

angular.module('app')
  .directive('cartItem', function () {
    return {
       scope: true,
       template: '<div class="cartItem"><div class="pull-left">' +
          '<p class="pull-left">{{ cartItem.brand_name }}' +
          '<a class="cartRemove" ng-click="removeItem(cartItem)">&nbsp {{removeItemLabel}}</a>' +
    '</p></div><p class="cartItemPrice pull-right">{{ cartItem.priceUnformatted }} {{symbol}}</p></div>'
    },
    link: function postLink(scope) {
        scope.removeItem = function(entity){
            scope.removeItemFromCart(entity);
        };
      }
  };
});

这将允许您的指令从当前控制器继承范围。我认为这就是你在这种情况下所需要的。这是关于范围和自定义指令的好文章:http://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/11/understanding-scopes-in-angularjs-custom-directives.aspx

答案 1 :(得分:0)

我使用隔离范围解决了它

    it('should call the remove function on click', function(){
        var isolateScope = element.isolateScope();
        spyOn(isolateScope, 'removeItemFromCart')
        isolateScope.removeItem();
        expect(isolateScope.removeItemFromCart).toHaveBeenCalled();
    });
相关问题