如何测试在角事件? [英] How can I test events in angular?
问题描述
我需要测试的事件得到正确排放或广播,手动触发事件。
I need to test that events get correctly emitted or broadcasted, and trigger events manually.
什么是做到这一点的最好方法是什么?
What's the best way to do this?
推荐答案
如果你只是需要对事件触发一些测试和追赶,这是我要做的事。为了确保某个事件被解雇( $发出
-ed或 $广播
-ed),间谍是路要走。您需要将调用 $发出
或 $广播
,然后只是做一些事情的范围参考像这样的:
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);
如果您不需要或不想要担心与传递的参数的 $发出
,你可以把一个 $关于
在 $ 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);
有关,当一个事件被捕获运行( $关于
),这是一个更容易一些测试功能。刚刚得到一个 $ 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
现在,我想这个事件的处理将在指令或控制器(或两者)是发生有关设置指令测试,看<一个href=\"https://github.com/vojtajina/ng-directive-testing\">https://github.com/vojtajina/ng-directive-testing.有关设置控制器测试,看<一个href=\"https://github.com/angular/angular-phonecat/blob/master/test/unit/controllersSpec.js#L27\">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
希望这有助于。
这篇关于如何测试在角事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!