jeudi 28 mai 2015

AngularJS jasmine service mock

There seems to be several ways to stub out services when testing Angular controllers using Jasmine.

One of the ways I've become accustomed to is to do the following in a beforeEach block:

mockService = {}

inject( $controller) ->
  controller = $controller('MyController', {
    MyRealService: mockService
  })

Another way is to use $provide to stub my dependency injected service:

module('app', ($provide) ->
  mockService = {}
  $provide.value('MyService', mockService)
)

When I had:

afterEach ->
  httpBackend.verifyNoOutstandingExpectation()

in my test. Only the $provide method worked, and the $controller style would not. Using $controller the test was somehow hitting MyRealService and including all of its dependencies, rather than ignoring and using mockService. Without the verifyNoOutstandingExpectation(), both methods seem to behave the same and the test passes.

What are the main differences between the 2 styles? When should you be using one over the other? Any ideas why the effect of stubbing is different in the presence of a verifyNoOutstandingExpectation()

Aucun commentaire:

Enregistrer un commentaire