如何在 AngularJS 中测试 $scope.$on [英] How do I test $scope.$on in AngularJS
问题描述
如何测试广播后是否填充了范围?我在 stackexchange 中搜索并找到了一些 QA,但没有一个回答我的问题.代码工作正常,只是不知道如何测试它.我可以补充一点,我是测试新手,尤其是 Jasmine.
How do I test that the scope is populated after the broadcast? I've searched and found a few QA's here in stackexchange, but none answered my problem. The code is working alright, just don't know how to test it. May I add that I'm a novice to testing, and especially with Jasmine.
所以,这里是代码:
服务 CrappySvc:
Service CrappySvc:
update: function() {
$rootScope.$broadcast('updatecrappy', Crappy.query());
}
控制器GetCrappyCtrl:
Controller GetCrappyCtrl:
$scope.$on('updatecrappy', function(event, crap) {
$scope.crap = crap;
});
茉莉花:
beforeEach(inject(function($rootScope, $httpBackend, $controller, Crappy) {
rootScope = $rootScope;
scope = $rootScope.$new();
Crappy = mockCrappy;
...
spyOn(rootScope, '$broadcast');
...
ctrl = $controller('GetCrappyCtrl', {
$scope : scope,
Crappy : mockCrappy
});
}));
it('$scope.$on should have been triggered', function() {
rootScope.$broadcast('updatecrappy', [{id : 2, name : 'crappy'}]);
expect(rootScope.$broadcast).toHaveBeenCalledWith('updscenes', [{id : 2, name : 'crappy'}]);
});
石头
推荐答案
你需要告诉 Jasmine 让 spy 调用实际的 $broadcast 函数
You need to tell Jasmine to let the spy call the actual $broadcast function
spyOn($rootScope, '$broadcast').andCallThrough();
如果你不使用 andCallThrough()
,间谍什么也不做.
If you don't use andCallThrough()
the spy does nothing.
编辑
对于 Jasmine 2,语法是
With Jasmine 2, the syntax would be
spyOn($rootScope, '$broadcast').and.callThrough();
这篇关于如何在 AngularJS 中测试 $scope.$on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!