2013-06-26 44 views
5

我是一位非常新的AngularJS和單元測試實踐的新手程序員。我花了數小時試圖找到解決辦法,但我越來越困惑。如果任何人都可以指出我正確的方向,我將不勝感激。我會盡量保持描述性。Karma/Jasmine Unit依賴性測試AngularJS服務

情況是這樣的:

我已經創造了AngularJS服務(服務A)有一對夫婦的功能。每個函數都會向REST API發出$ http GET請求,並返回包含JSON數據的$ http promise對象。在這些函數中,通過實現另一個非常簡單的服務(服務B)來構造URL,該服務已經作爲服務A的依賴注入。我創建了服務B的模擬,以將其與所有依賴關聯起來。這兩種服務都是在名爲「services」的同一模塊內部定義的。在這種情況下,並不需要這種依賴,但我只想了解它是如何工作的。

使用Jasmine,我想爲服務A構建一個單元測試,以確保它對API的請求被正確構建,並且可能返回正確的JSON數據。同時,我不希望任何真正的API調用。

這是我知道的:

$ httpBackend模擬是我需要的是能夠使虛擬來電的API,它提供的功能,預計某些請求並返回指定的結果。

我需要測試真正的服務A並注入我創建的服務B的模擬。我知道有辦法使用Jasmine Spies和$ provide來做到這一點。我也看到了使用sinon.js的例子,我不確定哪個是最好的方法。


我會在下面發佈我的源代碼,它是用CoffeeScript編寫的。

服務A:

'use strict' 

angular.module("services") 
    .service("ServiceA", ["$http", "ServiceB", ($http, ServiceB) -> 

    #Uses underscore.js to set this default attribute 
    defaults = withCredentials:true 

    getVarset: (itemName, options={}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("item/#{itemName}") 

     $http _.defaults(options, defaults) 

    getVarsets: (options = {}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("items") 

     $http _.defaults(options, defaults) 

    getModelsForVarset: (itemName, options = {}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("item/#{itemName}/prices") 

     $http _.defaults(options, defaults) 
    ]) 

服務B:

'use strict' 

angular.module('services') 
    .service 'ServiceB', [ -> 

    # Just return the string 
    # This service builds the real URL, but I've removed this 
    makeUrl: (Url) -> 
     "#{Url}" 
    ] 

回答

4

所以你是說你知道如何使用$提供/茉莉花間諜做到這一點,並正在尋找替代品?我主要只是使用$ provide/spy方法來進行嘲諷,到目前爲止它對我來說確實很好。

類似:

beforeEach(function() { 

    // set up a default value for your mock 
    bMock = { 
     makeUrl: jasmine.createSpy('makeUrl() mock').andReturn('http://www....') 
    } 

    // use the $provide service to replace ServiceB 
    // with your mock 
    module('services', function($provide) { 
     $provide.value('ServiceB', bMock); 
    }); 

}); 

it('should do what its supposed to do', function() { 
    // test... 
}); 

那麼,如果你想用$ httpBackend嘲笑在服務A的HTTP請求,你只需要使用$注射器服務搶$ httpBackend,然後調用。當(...)對它進行設置,一個la http://docs.angularjs.org/api/ngMock.$httpBackend

相關問題