I'm trying to test a controller method I have on the $scope. That method makes an async call and get a promise back. When the promise is resolved, the result is assign to a variable on the $scope.
The test I'm trying to come up with is simple: assign null to the $scope variable, call the method, wait for the call to finish, expect the result to be assign to the $scope variable.
For some reason, the promise never resolves. See http://plnkr.co/edit/qxs5Y54NvhA24Fk4MPv2?p=preview
Here is the controller method:
$scope.getSomething = ->
someFactory.find().then (response) ->
$scope.newValues = response.data
Now this is how I'm trying to test it:
it 'should get something', ->
scope.newValues = {}
scope.getSomething()
expect(scope.newValues.someData).toBeDefined()
For the purpose of the unit test, I'm mocking "someFactory" using the $q.when() method which, as far as I believe, should resolve immediately when passed an object. There's really no wait needed here. This is the mock factory:
mockSomeFactory = ($q) ->
{
find: ->
$q.when {someData: true}
}
And injecting it into the controller using $provide:
beforeEach module 'myAngularApp', ($provide) ->
$provide.factory "someFactory", mockSomeFactory
return
I tried to use Jasmine's runs, waits and waitsFor methods but no luck. WaitsFor would always fail, even after 5000 milliseconds. See http://plnkr.co/edit/s2OL56jVCRK0Ecyycoz0?p=preview
Anyone had this happen before?
angular promises are only resolved during the digest cycle. if you call $rootScope.apply() the promise should resolve.
You also needed to change the name of a variable: I updated the code http://plnkr.co/edit/dB6zTpZ1jYXOO1kGAYvb?p=preview
Using data to be consitant.
Hope this helps