How to mock AngularJS $resource with $promise.then in jasmine specs

故事扮演 提交于 2019-12-12 10:46:40

问题


I use $resource to set up some API calls, and while testing I have adopted the general approach of injecting $qand then doing

mockMyService.doSomethingAsync.andReturnValue($q.when(successResponse))

This has been working out pretty well, however, I have a method that looks like the following:

# MyService
MyService.doSomethingAsync(params).$promise.then ->
    $scope.isLoading = false

# MyService Spec
mockMyService = 
  doSomethingAsync: jasmine.createSpy('doSomethingAsync')

it 'calls service #doSomethingAsync', ->
  inject ($q) -> mockMyService.doSomethingAsync.and.returnValue($q.when(response))
  controller.methodThatWrapsServiceCall()
  scope.$apply()

  expect(mockMyService.doSomethingAsync).toHaveBeenCalled()

and unfortunately the mocking strategy outlined above doesn't seem to work when a $promise.then is chained at the end. I end up with the following error:

TypeError: 'undefined' is not an object (evaluating 'MyService.doSomethingAsync(params).$promise.then')

Methods that simply end with doSomethingAsync().$promise pass the tests without issues using this mocking strategy.

(Other info: These are Jasmine tests run with Karma and PhantomJS)


回答1:


Actually, figured it out!

I just changed my mock to return and.returnValue( { $promise: $q.when(response) } )



来源:https://stackoverflow.com/questions/29234920/how-to-mock-angularjs-resource-with-promise-then-in-jasmine-specs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!