我正在尝试为angularjs指令编写测试。该指令计算元素相对于窗口高度的高度。 该指令是使用谷歌闭包样式编写的(我是这种编写代码的新手,所以请随意纠正它。)
该指令运行正常但我在运行测试时遇到此错误:
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 :(得分:0)
您的问题不是您的代码。使用PhantomJS是一个缺陷或缺乏功能。出于某种原因,有人忘记包含Function.prototype.bind
。您可以在此处详细了解:https://github.com/ariya/phantomjs/issues/10522
根据我收集的内容,es5 shim应该可以解决问题。