[英]angular test not executing directive code
我在測試角度指令時遇到了一些麻煩。 這就是我的經歷。 我已經設置了業力來運行我的測試。 偽指令(帶有控制台日志“啟動計算”的部分)內的鏈接代碼似乎從未觸發過。 我不確定自己在做什么錯。 該測試工作符合我的期望-除了當我進入imageNode.style之外-那里什么都沒有。 沒有為圖像分配樣式。 為什么不觸發指令代碼? 有任何想法嗎?
這是我的模塊代碼。
(function() {
'use strict';
// sets narrower side of image to width of parent div
// used in sjwUserImage
angular.module('sjw.util', [])
.directive('imgFit', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.bind('load', function(e) {
console.log('kicking off calculations...');
console.log(element);
var parentWidth = element.parent().width();
if (this.naturalHeight > this.naturalWidth) {
// not horizontal or square
this.width = parentWidth;
}
else {
this.height = parentWidth;
}
});
}
};
});
})();
這是我的測試代碼。
describe('imgFit directive', function() {
var compile;
var scope;
var directiveElem;
console.log('loading sjw.util module...');
beforeEach(function(done) {
module('sjw.util', function() {
console.log('completed loading module.');
});
inject(function($compile, $rootScope) {
angular.module('sjw.util');
compile = $compile;
scope = $rootScope.$new();
directiveElem = getCompiledElement();
done();
});
});
function getCompiledElement() {
var myApp = angular.module('sjw.util');
var elem = angular.element(
'<div style="height:35px;width:35px">' +
'<img ' +
'ng-src="http://random_image_url" img-fit>' +
'</div>' +
'<div style="height:35px;width:35px">' +
'<img ' +
'ng-src="http://random_image_url" img-fit>' +
'</div>');
var compiledDirective = compile(elem)(scope);
scope.$digest();
return compiledDirective;
}
it('should assign width to parent width when image is square', function() {
var squareImageParent = directiveElem[0];
console.log(directiveElem);
expect(squareImageParent).not.toBe(null);
var imageNode = squareImageParent.childNodes[0];
expect(imageNode).toBeDefined();
console.log(imageNode);
console.log(imageNode.style);
//expect(imageNode.style.height == '35px').toBe(true);
});
});
我驅魔了這個惡魔。 我的問題是指令本身。 我正在使用的無頭瀏覽器中的圖像加載尚未完成。 因此,“ imgFit.link”中的“ load”事件將永遠不會觸發。 顯然是個問題。 這就是為什么插入我的超時(在上面的評論中)有幫助的原因。 它允許圖像完成加載。 駭客駭客,但似乎我無法得知幻影何時會加載圖像。
beforeEach(function(done) {
module('sjw.util');
inject(function($compile, $rootScope) {
compile = $compile;
scope = $rootScope.$new();
directiveElem = getCompiledElement();
// wait for the images to finish loading.
setTimeout(done, 2000);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.