Using AngularJS, CoffeeScript and Jasmine (edited in WebStorm), I would like to unit test a chain of promises.
Lets say I have the following example service:
Angular Service
class ExampleService
stepData: []
constructor: (@$http) ->
attachScopeMethod: (@scope) ->
@scope.callSteps = => @step1().then -> @step2()
step1: ->
@$http.get('app/step/1').then (results) =>
@stepData[0] = results.data
results
step2: ->
@$http.get('app/step/2').then (results) =>
@stepData[2] = results.data
results
This service allows me to attach a the method callSteps()
to the scope. This method, when called, executes a series of asynch $http calls to a 3rd party API.
To test that each step is at least called, I have written the following Jasmine spec.
Jasmine Spec
ddescribe 'ExampleService', ->
beforeEach ->
module 'myApp'
beforeEach inject ($rootScope, $injector) ->
@scope = $rootScope.$new()
@exampleService = $injector.get 'exampleService'
@q = $injector.get '$q'
describe 'process example steps', ->
beforeEach ->
@exampleService.attachScopeMethod(@scope)
it "should attach the scope method", ->
expect(@scope.callSteps).toBeDefined()
describe 'when called should invoke the promise chain', ->
it "should call step1 and step2", ->
defer = @q.defer()
@exampleService.step1 = jasmine.createSpy('step1').andReturn(defer.promise)
@exampleService.step2 = jasmine.createSpy('step2')
@scope.callSteps()
defer.resolve()
expect(@exampleService.step1).toHaveBeenCalled()
expect(@exampleService.step2).toHaveBeenCalled()
The results of this test is as follows:
- expect(@exampleService.step1).toHaveBeenCalled() - PASS
- expect(@exampleService.step2).toHaveBeenCalled() - FAIL
Can you tell me how I can get step2()
to succesfully run under test?
Thank you
EDIT
@Dashu below kindly supplied the answer to the problem. The trick is to simply call scope.$apply
or scope.$digest
to trigger the promise chain resolution.
So here is the working test fragment.
describe 'when called should invoke the promise chain', ->
it "should call step1 and step2", ->
defer = @q.defer()
defer.resolve()
@exampleService.step1 = jasmine.createSpy('step1').andReturn(defer.promise)
@exampleService.step2 = jasmine.createSpy('step2')
@scope.callSteps()
@scope.$apply()
expect(@exampleService.step1).toHaveBeenCalled()
expect(@exampleService.step2).toHaveBeenCalled()