如何测试$范围。在AngularJS美元 [英] How do I test $scope.$on in AngularJS
问题描述
我如何测试范围播出后填充?我已经搜查,并发现了一些质量保证是在这里stackexchange,但没有回答我的问题。在code是工作好了,只是不知道如何测试它。我可以补充一点,我是一个新手的测试,特别是与茉莉花。
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.
所以,这里的code:
So, here's the code:
服务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'}]);
});
石
推荐答案
您需要告诉茉莉花让间谍通话的实际$广播功能
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.
<一个href=\"https://jasmine.github.io/2.0/introduction.html#section-Spies:_<$c$c>and.callThrough</$c$c>\">Jasmine文档
修改
茉莉花2,语法为
spyOn($rootScope, '$broadcast').and.callThrough();
这篇关于如何测试$范围。在AngularJS美元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!