Angular测试不执行指令代码

angular test not executing directive code

本文关键字:指令 代码 执行 测试 Angular      更新时间:2023-09-26

我在测试angular指令时遇到了一些麻烦。这就是我所经历的。我已经安排好了卡玛来做测试。似乎指令中的链接代码(控制台日志"启动计算"的部分)从未真正触发。我不确定我做错了什么。测试的工作方式与我所期望的一样——除了当我深入到imageNode时。风格——里面什么都没有。没有为图像分配样式。为什么指令代码没有被触发?什么好主意吗?

这是我的模块代码

(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中的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);
    });
  });