2015-11-05 57 views
0

我們使用角1.2.x(我們必須由於IE8)。我們正在測試Karma和Jasmine。我想測試我的模塊的行爲,以防服務器響應一個錯誤。據角文檔,我應該只是簡單地準備$ httpBackend模擬這樣的(正是我所期待):

authRequestHandler = $httpBackend.when('GET', '/auth.py'); 

// Notice how you can change the response even after it was set 
authRequestHandler.respond(401, ''); 

這是我在做什麼在我的測試:

beforeEach(inject(function($injector) { 
    keepSessionAliveService = $injector.get('keepSessionAliveService'); 
    $httpBackend = $injector.get('$httpBackend'); 
    $interval = $injector.get('$interval'); 
})); 

(...) 

describe('rejected keep alive request', function() { 
    beforeEach(function() { 
     spyOn(authStorageMock, 'get'); 
     spyOn(authStorageMock, 'set'); 

     $httpBackend.when('POST', keepAliveUrl).respond(500, ''); 

     keepSessionAliveService.start('sessionId'); 
     $interval.flush(90*60*1001); 
     $httpBackend.flush(); 
    }); 

    it('should not add the session id to the storage', function() { 
     expect(authStorageMock.set).not.toHaveBeenCalled(); 
    }); 
}); 

但是測試失敗了,因爲模擬函數被調用,我可以在代碼覆蓋中看到它從不會運行到我傳遞給§promise的錯誤函數中,然後作爲第二個參數。

顯然我在這裏做錯了什麼。它可能需要使用我們正在使用的較老的角度版本嗎?

任何幫助,將不勝感激!

回答

0

事情是這樣的:

it("should receive an Ajax error", function() { 
     spyOn($, "ajax").andCallFake(function(e) { 
      e.error({}); 
     }); 

     var callbacks = { 
      displayErrorMessage : jasmine.createSpy() 
     }; 

     sendRequest(callbacks, configuration); 
     expect(callbacks.displayErrorMessage).toHaveBeenCalled();