Angular:如何监视 $element.on [英] Angular: How to spy on $element.on

查看:25
本文介绍了Angular:如何监视 $element.on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令,它在其 link 函数中执行类似的操作

I have a directive which does something like this in its link function

angular.module('myApp')
    .directive('barFoo', function() {
        return {
            restrict: 'E',
            link: function (scope, element) {
                element.on('click', ....);
            }
        };
    });

现在我想在我的单元测试中验证它是否正确调用了 on

Now I would like to verify in my unit test that it calls on correctly

element = angular.element('<bar-foo></bar-foo>');
$compile(element)(scope);
spyOn(element, 'on');
...
expect(element.on).toHaveBeenCalled();

它告诉我没有调用间谍.从我在网上找到的内容来看,angular/jquery 每次都会围绕 DOM 元素创建一个新的包装器.这意味着我的指令中的 element 与我的规范文件中的元素不同.很可能(未验证) element[0] 可能是相同的.我还试图监视 angular.element

It tells me the spy is not called. From what I've found on the web, angular/jquery creates a new wrapper around the DOM element every time. Meaning the the element inside my directive is not the same as the element in my spec file. Most likely (not verified) the element[0] probably are the same. I've also tried to spy on angular.element

var mockEl = { on: angular.noop };
spyOn(angular, 'element').andReturn(mockEl);
spyOn(mockEl, 'on');

但这似乎破坏的比它修复的要多(例如,我还需要像 isloateScope 这样的函数).

but that seems to break more than it fixes (I also need functions like isloateScope for example).

无论如何,是否有一些简单的方法可以监视指令中使用的元素的 on 函数?

Anyway, is there some easy way I can spy on the on function of the element used inside a directive?

推荐答案

链接功能可以单独测试

element = angular.element('<bar-foo');
spyOn(element, 'on');
BarFooDirective[0].link(scope, element);
expect(element.on).toHaveBeenCalled();

如果它足够简单(远离属性、必需的控制器、依赖项),否则规范会导致更多问题,无法解决.

if it is simple enough (stays away from attrs, required controllers, dependencies), otherwise the spec will cause more problems than it can solve.

否则可以测试喜欢由框架完成:

element = angular.element('<bar-foo');
expect(angular.element._data(element[0]).events.click).toBeDefined();

对于可能在其自身或子指令中定义多个 click 侦听器的实际指令,仅确保侦听器存在是不够的.通常,您可能希望封装内部函数,但匿名点击处理程序也可以暴露于范围以进行测试:

For real-world directive which may have more than one click listener defined in either itself or child directives it is not enough to make sure that listeners exist. Generally you may want to encapsulate internal functions, but anonymous click handler can also be exposed to scope for the purpose of testing:

element = angular.element('<bar-foo');
expect(angular.element._data(element[0]).events.click).toContain(scope.onClick);

这篇关于Angular:如何监视 $element.on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆