Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 260
bahrieinn Avatar asked Mar 24 '15 14:03

bahrieinn


1 Answers

Actually, figured it out!

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

like image 164
bahrieinn Avatar answered Nov 29 '22 08:11

bahrieinn