如何测试在AngularJS广播事件 [英] How can I test Broadcast event in AngularJS
问题描述
我有一个控制器,它发射的rootscope广播事件。我想测试该broacast事件正确解雇了。
I have a controller which emits a broadcast event on the rootscope. I would like to test that the broacast event is fired correctly.
在我的控制器我的code是这样的:
My code in my controller looks like this:
$scope.$watch("pageIndex", function(){
if($scope.pageIndex == 4)
{
// emit social share
$rootScope.$broadcast('myEvent');
}
});
我曾尝试用下面的code来测试它:
I have tried to test it with the following code:
it('Should call myEvent when pageIndex is 4',function(){
scope.pageIndex = 4;
scope.$apply();
expect(rootScope.$on).toHaveBeenCalledWith('myEvent');
});
但它告诉我,在code不叫,我已经测试了手动,它确实。我已经然后执行下述code尝试:
But it tells me that the code isn't called, which I have manually tested that it does. I have then tried with the following code:
it('Should call myEvent when pageIndex is 4',function(){
var listener = jasmine.createSpy('listener');
rootScope.$on('myEvent', listener);
scope.pageIndex = 4;
scope.$apply();
expect(listener).toHaveBeenCalled();
});
但是具有相同的阴性结果。有没有一种方法来测试,一个事件被广播?
But with the same negative result. Is there a way to test that an event is broadcasted?
推荐答案
假设你用茉莉花,对我来说是伟大的工作如下。
Assuming you're using Jasmine, the following is working great for me.
... other unit test setup code ...
var rootScope;
beforeEach(inject(function($injector) {
rootScope = $injector.get('$rootScope');
spyOn(rootScope, '$broadcast');
}));
describe("my tests", function() {
it("should broadcast something", function() {
expect(rootScope.$broadcast).toHaveBeenCalledWith('myEvent');
});
});
如果你正在广播消息,并附着对象,你甚至可以测试对象达到预期
If you're broadcasting a message and attaching objects to it, you can even test that the objects match expectations
someObj = { ... something ... };
expect(rootScope.$broadcast).toHaveBeenCalledWith('someEvent', someObj);
这篇关于如何测试在AngularJS广播事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!