How do I test $scope.$on in AngularJS

前端 未结 4 1343
Happy的楠姐
Happy的楠姐 2020-12-31 00:54

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

相关标签:
4条回答
  • 2020-12-31 01:26

    If want to fake the returnValue from $scope.$broadcast() you can do something like these two cases:

    Case 1:

    scope.$broadcast('TEST_CHANGED', {test: 'test1'});
    spyOn(scope, '$broadcast').and.callThrough();
    expect(something).toEqual('something');
    

    Case 2:

    scope.$broadcast('TEST_CHANGED', {test: 'test2'});
    spyOn(scope, '$broadcast').and.callThrough();
    expect(something2).toEqual('something2');
    
    0 讨论(0)
  • 2020-12-31 01:28

    As far as "toHavebeenCalled" concerned, there is no need of "andCallThrough()". Simple spy would work. In your case your arguments are different.

    You are broadcasting like, rootScope.$broadcast('updatecrappy', [{id : 2, name : 'crappy'}]);

    But you expect :

    expect(rootScope.$broadcast).toHaveBeenCalledWith('updscenes', [{id : 2, name : 'crappy'}]);

    look at argument " updarecrappy" but in tohavebeencalled it is "updscenes".

    0 讨论(0)
  • 2020-12-31 01:43

    You need to tell Jasmine to let the spy call the actual $broadcast function

    spyOn($rootScope, '$broadcast').andCallThrough();
    

    If you don't use andCallThrough() the spy does nothing.

    Jasmine Docs

    EDIT

    With Jasmine 2, the syntax would be

    spyOn($rootScope, '$broadcast').and.callThrough();
    
    0 讨论(0)
  • 2020-12-31 01:44

    Look at the sample code below, it works well for me.

    Emitting sample event 'onTimeChanged' from $rootScope. My controller has a listener 'onTimeChanged' and I am calling a method timeChanged() inside it.

    describe('onTimeChanged()', function() {
        it('should call another method or controller', function() {
            spyOn(searchCtrl, 'timeChanged');
            $rootScope.$emit('onTimeChanged');
            expect(searchCtrl.timeChanged).toHaveBeenCalled();
        });
    });
    

    Note that I did not spy on method '$emit' of rootScope.

    0 讨论(0)
提交回复
热议问题