0

I am trying to pass a simulate time passing in an angularjs jasmine test.

My directive that I am testing simply displays the current time and updates every second:

return {
  restrict: 'A',
  scope: {
    format: '@'
  },
  link: function (scope, element, attrs) {

    var timeout;

    function updateElement() {
      if (scope.format) {
        element.text($filter('date')(new Date(), scope.format));
      }
    }

    function updateTime() {
      updateElement();
      timeout = $timeout(function () {
        updateTime();
      }, 1000);
    }

    element.bind('$destroy', function () {
      $timeout.cancel(timeout);
    });

    updateTime();
  }
};

In my test I need to simulate time passing. I tried with $timeout and $timeout.flush but I think I am using it wrong:

it('should update every second', function () {
  $scope.$digest();
  console.log('before: ' + element.text());
  var before = element.text();

  // Wait for a couple seconds...
  $timeout(function () {
    $scope.$digest();
    console.log('after: ' + element.text());
    expect(element.text()).not.toEqual(before);
  }, 5000);

  $timeout.flush(5000);
});

Should I use $timeout to simulate time passing by or is their another method to do so?

Plunker: http://plnkr.co/edit/0V4AFGXqSfc9iLCuZbvn?p=preview

1 Answer 1

1

If you wrap the $scope.$digest() inside a setTimeout it should work. Like so:

setTimeout(function(){
  $timeout.flush();
  console.log('after: ' + element.text());
  expect(element.text()).not.toEqual(before);
}, 5000);

$timeout.flush() works in tests by just calling all the callbacks registered by $timeout regardless of their time value so you have to do the timeout outside of angular in this case. As you're only looking for a change every second your code would be calling updateElement() twice within one second.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.