2013-10-18 34 views
20

如何在廣播後測試範圍是否已填充?我已經在stackexchange中搜索並發現了幾個QA,但沒有人回答我的問題。代碼工作正常,只是不知道如何測試它。我可以補充一點,我是測試的新手,尤其是與Jasmine。

所以,這裏是代碼:

服務CrappySvc:

update: function() { 
    $rootScope.$broadcast('updatecrappy', Crappy.query()); 
} 

控制器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'}]); 

});

+0

我覺得這也有幫助:http://stackoverflow.com/questions/15272414/how-can-i-test-events-in-angular – Ben

回答

36

你需要告訴茉莉花讓間諜呼叫實際$廣播功能

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

如果不使用andCallThrough()間諜什麼都不做。

Jasmine Docs

編輯

茉莉2,語法將

spyOn($rootScope, '$broadcast').and.callThrough(); 
+0

我們可以詳細說明這實際上是在做什麼? – iamwhitebox

+0

@whitebox就是這樣,它並沒有真正做得太多。默認情況下,Jasmine的間諜會替換正在偵測的原始函數。調用'and.callThrough()'會增加默認的行爲,並使得間諜也*調用正在被窺探的原始函數。這確實是它所做的一切。 – ivarni

+0

你不需要在這種情況下的和.allThrough()如果你只是斷言廣播被稱爲 –

0

如果要僞造returnValue$scope.$broadcast()你可以做一些這樣的兩種情況:

案例1:

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

案例2:

scope.$broadcast('TEST_CHANGED', {test: 'test2'}); 
spyOn(scope, '$broadcast').and.callThrough(); 
expect(something2).toEqual('something2'); 
0

至於 「toHavebeenCalled」 而言,沒有必要 「andCallThrough()」 中。簡單的間諜會工作。在你的情況下你的論點是不同的。 $廣播('updatecrappy',[{id:2,name:'crappy'}]);

但你想到:

預期(rootScope $播出。).toHaveBeenCalledWith('updscenes',[{ID:2,名稱: '蹩腳'}]);

看看參數 「updarecrappy」,但在tohavebeencalled是 「updscenes」。

0

請看下面的示例代碼,它適用於我。

從$ rootScope發射示例事件'onTimeChanged'。我的控制器有一個監聽器'onTimeChanged',我在裏面調用一個方法timeChanged()。

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

請注意,我沒有窺探rootScope的方法'$ emit'。