2014-07-14 76 views
4

我有一個角度測試問題。我試圖測試$廣播是否成功解僱。我有一些奇怪的行爲,試圖使用spyOn。如果您有任何建議,請幫助我一直試圖解決這個問題好幾個小時。我的測試是這樣的:

describe('Signup controller', function() { 

    beforeEach(module('myApp')); 

    describe('SignupCtrl', function(){ 
    var $scope, ctrl, $httpBackend, AUTH_EVENTS, $rootScope; 

    beforeEach(inject(function($injector, $controller, 
     _$httpBackend_, _apiUrl_, _AUTH_EVENTS_){ 

     $rootScope = $injector.get('$rootScope'); 
     $scope = $rootScope.$new(); 
     ctrl = $controller('SignupCtrl', {$scope: $scope}); 
     $httpBackend = _$httpBackend_; 
     apiUrl = _apiUrl_; 
     AUTH_EVENTS = _AUTH_EVENTS_; 
     spyOn($rootScope, "$broadcast"); 
     } 
    )); 

    afterEach(function() { 
     $httpBackend.verifyNoOutstandingExpectation(); 
     $httpBackend.verifyNoOutstandingRequest(); 
    }); 

    it('should show error message from API', function() { 
     var apiMessage = 'That email already exists.'; 
     $httpBackend.expectPOST('/users').respond(400, { 
     message: apiMessage 
     }); 

     // call controller register function with mock empty credentials 
     $scope.register({}); 

     $httpBackend.flush(); 
     expect($rootScope.$broadcast).toHaveBeenCalledWith(AUTH_EVENTS.signupFailed); 
     expect($scope.errorMessage).toBe(apiMessage); 
     expect($scope.showErrorMessage).toBe(true); 
    }); 

    }); 
}); 

而我得到的錯誤是:

TypeError: 'undefined' is not an object (evaluating '$rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). 
      defaultPrevented') 
    at /src/web/src/vendor-bower/angular/angular.js:9789 
    at /src/web/src/vendor-bower/angular/angular.js:12595 
    at /src/web/src/vendor-bower/angular/angular.js:12407 
    at /src/web/src/vendor-bower/angular-mocks/angular-mocks.js:1438 
+0

我認爲這是相關的:http://stackoverflow.com/questions/22721657/typeerror-cannot-read-property-defaultprevented-of-undefined –

回答

12

嘗試spyOn(rootScope,'$broadcast').andCallThrough();,讓我知道如何去。另請參閱我的評論。

+4

它實際上工作。感謝亞歷克斯這一段時間讓我煩惱。在jamsine 2.0中它只有一個註釋,它和.CallThrough(); – iblazevic

+0

我知道對了......這個迷住了我一個多月...... –

+0

謝謝,我非常惱火這些問題。它在遷移到ui-router後突然出現。 –