AngularJS: test $scope methods that make async cal

2019-08-31 03:20发布

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?

1条回答
家丑人穷心不美
2楼-- · 2019-08-31 04:07

angular promises are only resolved during the digest cycle. if you call $rootScope.apply() the promise should resolve.

root.$apply()
expect(scope.newValues.data).toBeDefined()

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.

    $scope.newValues.data = response.data

# mock factory
mockSomeFactory = ($q) ->
{
  find: ->
    $q.when {data: true}
}

Hope this helps

查看更多
登录 后发表回答