2017-01-02 46 views
2

我的服務(廠)是這樣的:測試AngularJS服務(廠)有因果報應和茉莉花

angular.module('App') 
    .factory('SalesService', function($http) { 
    return { 
     getSales: function(data) { 
     return $http.get('/sales'); 
     } 
    } 
}) 

意外的請求:GET /銷售當我這樣做:

describe('Sales Services', function() { 

    beforeEach(module('App')); 

    it('should get the sales data', inject(function(SalesServices, $httpBackend) { 
    SalesServices.getSales().then(function(data) { 
     expect(data.success).toBeTruthy(); 
    }); 
    $httpBackend.flush(); 
    })); 

}); 

一切對我來說似乎沒問題。我做錯了什麼?

+0

這裏輸入錯誤:.getSaless() – ppasler

+0

@ppasler修復了輸入錯誤,我確定這不是問題 –

+0

另一個:'SalesServices'和工廠創建'SalesService'而沒有's' – ppasler

回答

0

爲了不inject在所有測試你的依賴,你應該使用beforeEach

var $httpBackend, SalesService; 

beforeEach(module('App')); 

beforeEach(inject(function (_$httpBackend_, _SalesService_) { 
    $httpBackend = _$httpBackend_; 
    SalesService = _SalesService_; 
})); 

然後,在您的測試,你應該預期調用一些網址:

it('should get the sales data', function() { 
    // given 
    var response = { data: 'result' }; 
    var result = {} 
    $httpBackend.expect('GET', '/sales').respond(200, response); 

    // when 
    SalesService.getSales().then(function (responseData) { 
    result = responseData; 
    }); 
    $httpBackend.flush(); 

    // then 
    expect(result).toEqual(response); 
}); 

最後,您需要確保沒有待處理的請求:

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

響應方法在做什麼$ httpBackend.expect('GET','/sales').respond(200,response); '?我的get不接受任何請求param,爲什麼我需要在這裏傳遞響應對象? –

+0

和第5行的'suite'是從哪裏來的? –

+0

@ThianKianPhin你現在可以忽略套件對象,我將它刪除。這是我們稍後可以討論的額外優化。 – tomepejo