javascript - 如何在 AngularJS/Jasmine 单元测试中模拟图像加载事件?

标签 javascript angularjs image events jasmine

我正在尝试对如下所示的简单指令进行单元测试:

angular.module('blog').directive('imageOnLoad', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, fn) {

            element.bind('load', function() {
                scope.$emit('resizeContent');
            });

        }
    };
});

我可以看到我需要在这里测试的两件事是它绑定(bind)到图像加载事件,该事件又会发出 resizeContent 事件。

我的单元测试中有以下内容 - 目前只是测试事件绑定(bind):

describe('imageOnLoad', function() {

  beforeEach(module('blog'));

  var scope,compile, element;

  beforeEach(inject(function($rootScope,$compile) {
    scope = $rootScope.$new();
    compile = $compile;

    var elementString = '<img ng-src="123.jpg" image-on-load />';
    element = $compile(elementString)(scope);
  }));

  it('should bind to the load event of the image', function() {

    spyOn(element, 'bind').andCallThrough();

    expect(element.bind).toHaveBeenCalled();

  });
});

我的问题:加载事件似乎永远不会触发。我的第一个猜测是,这是因为 123.jpg 图像不存在 - 如果是这样,我的问题是如何模拟它,这样我就不必在其中携带物理图像文件。

最佳答案

成功了,也是我设置顺序的问题。它通过调用隐式测试图像加载事件绑定(bind)。这是工作代码:

describe('imageOnLoad', function() {

  beforeEach(module('blog'));

  var scope,compile, element;

  beforeEach(inject(function($rootScope,$compile) {
    scope = $rootScope.$new();
    compile = $compile;

    element = angular.element('<img ng-src="123.jpg" image-on-load />');
    $compile(element)(scope);
  }));

  it('should emit the resizeContent signal when the load event occurs', function() {

    spyOn(scope, '$emit');
    element.trigger('load');
    expect(scope.$emit).toHaveBeenCalledWith('resizeContent');

  });
});

关于javascript - 如何在 AngularJS/Jasmine 单元测试中模拟图像加载事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621168/

相关文章:

Java:使用WritableRaster.setRect来叠加图像?

image - Octave 4.2.1 中的简单绘图错误

javascript - 以编程方式设置标签文本会忽略 ExtJS 中的换行符

javascript - 将固定的 div 保留在其容器中

javascript - 绕过 XHR 的 CSRF 保护是否安全? ( rails )

css - 从可拖动的 angular-dnd-list div 复制文本

javascript - 将重复项合并到数组中

angularjs - 如何获取 angularjs 范围 id

css - 使用 html5 向图像添加标题的正确方法是什么

javascript - CK编辑器config.js更改不起作用(基本版本)