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

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

问题描述

我有一个指令在链接中执行类似的操作函数

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

现在我想在我的单元测试中验证它在上调用正确

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元素周围创建一个新的包装器。这意味着我的指令中的元素与我的spec文件中的元素不同。很可能(未经验证)元素[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).

无论如何,我可以通过一些简单的方法监视上的 $ c>指令内使用的元素的功能?

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();

如果它足够简单(远离attrs,所需的控制器,依赖项),否则规范将造成的问题比它解决的问题多。

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();

对于可能有多个的真实世界指令,请点击在自身或子指令中定义的侦听器不足以确保侦听器存在。通常,您可能希望封装内部函数,但也可以将匿名单击处理程序公开到作用域以进行测试:

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天全站免登陆