0
votes

I've written a Factory with AngularJs which have a method that returns an http promise.

'use strict'

angular.module('projDefinitApp')
.factory 'testService', ($http) ->
  {  getTest: (testID) ->
    $http.get "temp/test.json"
  }

I'm having some issues when making a test, using karma and Jasmine. The promise didn't return any result. I tried to create a var, then call the function and change the value of the var. But it does not updates the value:

'use strict'
describe 'Service: testService', ->
  # load the service's module
  beforeEach module 'projDefinitApp'

  # instantiate service
  testService = {}
  beforeEach inject (_testService_) ->
    testService = _testService_

  it 'should do something', ->
    retrieved = undefined
    testService.getTest().success ($data,retrieved) ->
      retrieved = $data
      return
    expect(retrieved).toBe(null)
    return
  return

The console exit looks like this

PhantomJS 1.9.8 (Linux) Service: testService should do something FAILED

Expected undefined to be null.

1

1 Answers

2
votes

in tests, Angular does not immediately perform requests made by the $http service. The reason being that all requests are queued up to be run in the $digest phase of the Angular lifecycle. You will need to run through Angular’s digest cycle manually in tests by calling $rootScope.$apply() or $httpBackend.flush() which will make the call internally.

One issue I see in the current test is that the tests aren’t made to work asynchronously, there is no guarantee that retrieved will be set before the expectation is called since the promises are resolved asynchronously. You rewrite the tests to make it work asynchronously:

it 'should do something', (done) ->
  testService.getTest().success ($data) ->
    expect($data).toBe(null)
    done()
    return

  $rootScope.$apply()
  return
return