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