我有一个控制器,它依赖于通过 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 作为 [Function] 返回。
我的问题是:
如何驱动 Jasmine 测试以正确进入服务并获取响应?有没有办法为服务创建直接的单元测试?
任何和所有的帮助表示赞赏