jeudi 4 juin 2015

Unit testing controller when $timeout is called within an init() function

I am trying to run a jasmine test in visual studios using chutzpah/test explorer.

I have a controller that looks like this:

function ctrl($scope, $timeout, resolvedData) {
  var vm = this;
  vm.data;
  init();

  function init() {
    if(resolvedData.lenth > 0) {
      $timeout(function() {
        vm.data = resolvedData;
      }, 0);
    };
  };
}

My test file looks like this:

describe('ctrl', function() {
  var ctrl,
      resolvedData,
      $controller,
      $timeout,
      $scope;
  var mockResolvedData = [{}, {}, {}];

  beforeEach(function() {
    module('app');
    inject(function(_$controller_, _$rootScope_, _$timeout_) {
      $scope = _$rootScope.$new();
      $controller = _$controller_;
      $timeout = _$timeout_;
      resolvedData = mockResolvedData;
      ctrl = $controller('ctrl', {$scope: $scope, resolvedData: resolvedData, $timeout: $timeout})
    })
  })

  it('should set data when the controller loads', function() {
    $timeout.flush();
    expect(ctrl.data).toEqual(mockResolvedData);
  })
})

When I add the $timeout.flush(), I get this error:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

Taking out the $timeout.flush() gives me this error:

Expected undefined to equal [ { }, { }, { } ].

Adding $scope.$apply() before the expect (instead of $timeout.flush()) gives me this:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

Is there something else that I am missing? I want to test that vm.data gets set when the controller loads after the function from $timeout is called but no luck.

Aucun commentaire:

Enregistrer un commentaire