2

Я пытаюсь написать тест для директивы angularjs. Директива вычисляет высоту элемента по отношению к высоте окна. Директива написана с использованием стиля закрытия Google (я новичок в этом стиле написания кода, поэтому, пожалуйста, не стесняйтесь исправить его).Карма тест для угловой директивы с введенным окном

директива работает отлично, но я получаю эту ошибку при выполнении теста:

TypeError: 'undefined' is not a function (evaluating 'this.link.bind(this)') 

Я также не вводил в окно, на самом деле не знает, как это сделать, любая помощь будет принята с благодарностью.

директива (который работает):

(function(){ 
/** 
    Constant, size of bottom padding. 
*/ 
var PADDING_BOTTOM = 45; 

/** 
* @constructor 
*/ 
var Directive = function($window) { 
    this.link = this.link.bind(this); 
    this.$window = $window; 

    this.scope; 
    this.elem; 
    this.attrs; 
}; 

/** 
* Height Calculator directive factory. Entry point and used in `module.directive`. 
*/ 
Directive.factory = function($window) { 
    var dir = new Directive($window); 
    return { 
     link: dir.link 
    }; 
}; 

/** 
* Linking function. 
*/ 
Directive.prototype.link = function(scope, elem, attrs) { 
    var that = this; 
    this.scope = scope; 
    this.elem = elem; 
    this.attrs = attrs; 

    var w = angular.element(this.$window); 

    // Created a function that can watch the 
    // width of the window so we know when its changed 
    this.scope.getWindowHeight = function() { 
     return w.height(); 
    }; 

    // Watch for the size of the window changing 
    this.scope.$watch(that.scope.getWindowHeight, function (newWidth, oldWidth) { 
     var offset = that.elem.offset().top; 
     var window_height = that.$window.innerHeight; 

     var iframeHeight = window_height - offset - PADDING_BOTTOM; 

     that.elem.height(iframeHeight); 
    }); 

    // Capture the window event so we can capture window resize event 
    w.bind('resize', function() { 
     that.scope.$apply(); 
    }); 
}; 

app.directive('heightCalculator', Directive.factory); 

})(); 

и это испытание карма:

describe('HeightCalculator directive', function() { 


    beforeEach(module('myApp')); 
    beforeEach(inject(function(_$compile_, _$rootScope_) { 
     $compile = _$compile_; 
     $scope = _$rootScope_.$new(); 
    })); 

    it('should be the height of the window minus position on page minus padding bottom', inject(function($rootScope, $controller) { 

     var element = angular.element("<div height-calculator>test div</div>"); 

     $compile(element)($scope); 

    })); 
}); 
+0

Вам не нужно вводить '$ window' в тесты. Вероятно, ошибка возникла в результате создания такого типа, которое является самым ужасным из того, что я видел за многие годы. Это то, что я называю чрезмерным чрезмерным созданием директивы. Я постараюсь сделать это как «нормальный», и он должен работать. –

+0

Директива сама по себе прекрасно работает, но не тест. Я делал это «как обычно», однако недавно начал читать о компиляторе Google закрытия - см .: http://www.mircozeiss.com/a-radical-new-approach-to-developing-angularjs-apps/ и http : //google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.html –

ответ

0

Ваша проблема не ваш код. Это дефект или недостаток функциональности с помощью PhantomJS. По какой-то причине кто-то забыл включить Function.prototype.bind. Вы можете узнать больше об этом здесь: https://github.com/ariya/phantomjs/issues/10522

Из того, что я собрал, es5 shim должен сделать трюк.

Смежные вопросы