我是一位非常新的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}"
]