Angularjs - test $ timeout on the callback of an asynchronous function

1

I have the code for the following asynchronous function:

obj.save({
  success: function(data) {
    $timeout(function() {
      defer.resolve(data);
    });
  }
});

And in my test I have:

var $rootScope, $compile, $timeout;

beforeEach(inject(function(_$rootScope_, _$compile_, _$timeout_) {
  $compile = _$compile_;
  $rootScope = _$rootScope_;
  $timeout = _$timeout_;
}));

it("updates angular $rootScope", function() {
  $rootScope.obj = null;

  var element = $compile('<input ng-model="obj" type="text">')($rootScope);
  expect(element.val()).toBe('');

  obj.save().then(function(data) {
    $rootScope.obj = "test";
  });
  $timeout.flush();

  expect(element.val()).toBe('test');
});

It gives an error because it has not yet passed $ timeout () Error: No deferred tasks to be flushed

Any ideas how I can resolve this?

    
asked by anonymous 23.02.2014 / 00:21

1 answer

0

I found the answer, what I needed to do in my test was:

it("updates angular $scope", function() {
  $rootScope.obj = null;

  var element = $compile('<input ng-model="obj" type="text">')($rootScope);
  expect(element.val()).toBe('');

  runs(function() {
    obj.save().then(function(data) {
      $rootScope.obj = "test";
    });
  });

  waitsFor(function() {
    try {
      $timeout.flush();
    } catch(err) {}
    return $rootScope.obj !== null;
  });

  runs(function() {
    expect(element.val()).toBe('test');
  });
});

And so it works.

    
23.02.2014 / 00:21