ngResourceを介して構築されたサービスに依存するコントローラーがあります。私はこれをテストするのに問題があります(実際のアプリケーションでは両方とも魅力のように機能しているように見えますが)。以下は(サニタイズされた)コントローラーです
MyApp.Controller.MyCarsController = (scope, http, typeService) ->
if scope.context==undefined
scope.ferrari_or_porshe =""
scope.id = ""
else if scope.context=="ferrari"
scope.country_or_pi ="Ferrari"
else if scope.context=="porshe"
scope.country_or_pi ="Porshe"
typeService.index
ferrari_or_porshe: scope.ferrari_or_porshe
id: scope.id
, (response) ->
scope.type = response
scope.loading = false
MyApp.Controller.MyCarsController.$inject = ['$scope', '$http', 'Type']
そしてこれがサービスです:
MyApp.MyModule.factory 'Type', ['$resource', ($resource) ->
TypeResource = $resource("/api/types/:ferrari_or_porshe/:id", {},
index:
method: "GET"
isArray: true
)
return TypeResource
]
最後に、いくつかのテストコード:
describe 'MyApp.Controller.MyCarsController', ->
beforeEach module('MyModule')
beforeEach inject ($rootScope, $http, $controller, Type) ->
@scope = $rootScope.$new()
@typeService = Type
@scope.context = undefined
$controller 'MyApp.Controller.MyCarsController', $scope: @scope
describe '#home-page', ->
it 'contains a list of types', ->
expect(@scope.types.length).toBeGreaterThan 0
it "sets instance variables correctly", ->
expect(@scope.ferrari_or_porshe).toBe ""
expect(@scope.id).toBe ""
これは失敗します:
No more request expected in helpers/angular-mocks.js on line 889
TypeError: 'undefined' is not an object (evaluating 'this.scope.types.length') in controllers/my_cars_controller_spec.js
console.logsを適切に適用することにより、応答の最終コールバックに到達しないことが問題であることがわかりました。TypeResourceは[関数]として返されます。
私の質問は:
ジャスミンテストを実行してサービスに正しく入り、応答を取得するにはどうすればよいですか?また、サービスの直接単体テストを作成する方法はありますか?
ありとあらゆる助けをいただければ幸いです