如何以角度测试事件

如何以角度测试事件

本文介绍了如何以角度测试事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试事件是否正确发出或广播,并手动触发事件.

I need to test that events get correctly emitted or broadcast, and trigger events manually.

最好的方法是什么?

推荐答案

如果您只需要对事件触发和捕获进行一些测试,我就是这样做的.为了确保某个事件被触发($emit-ed 或 $broadcast-ed),间谍是要走的路.您需要对将调用 $emit$broadcast 的作用域的引用,然后执行如下操作:

If you're just needing some testing on event firing and catching, this is how I do it. For ensuring that a certain event gets fired ($emit-ed or $broadcast-ed), a spy is the way to go. You need a reference to the scope that will be calling the $emit or $broadcast, and then just to do something like this:

spyOn(scope, "$emit")
//run code to test
expect(scope.$emit).toHaveBeenCalledWith("MY_EVENT_ID", other, possible, args);

如果您不需要或不想担心通过 $emit 传递的参数,您可以在 $emit 上放置一个 $oncode>$rootScope 并设置一个标志以了解事件已发出.像这样:

If you don't need or don't want to worry about the arguments that are passed with the $emit, you can put an $on on the $rootScope and set a flag to know the event was emitted. Something like this:

var eventEmitted = false;
$rootScope.$on("MY_EVENT_ID", function() {
   eventEmitted = true;
});
//run code to test
expect(eventEmitted).toBe(true);

对于在捕获事件时运行的测试功能 ($on),要简单一些.只需从 inject 函数中获取一个 $rootScope,然后发送所需的事件.

For testing functionality that runs when an event is caught ($on), it's a little easier. Just get a $rootScope from the inject function and then send the desired event.

$rootScope.$broadcast("EVENT_TO_TEST", other, possible, args);
//expects for event here

现在,我想这个事件处理将在指令或控制器(或两者)中发生.有关设置指令测试,请参阅 https://github.com/vojtajina/ng-directive-testing.有关设置控制器测试,请参阅 https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L27

Now, I imagine this event handling would be happening in a directive or a controller (or both) For setting up directive tests, see https://github.com/vojtajina/ng-directive-testing. For setting up controller tests, see https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L27

希望这会有所帮助.

这篇关于如何以角度测试事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:17