Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<html>
<head>
<title>Interval Ticker Example</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular-mocks.js"></script>
</head>
<body>
<script type="text/javascript">
var app = angular.module('calculatorApp', []);
app.controller('CalculatorController', function calculatorController($scope, $interval) {
var counterInstance;
var counterFunction = function(start, inc) {
if ($scope.ticker === 0 && start)
$scope.ticker = start;
if (!inc)
inc = 1;
$scope.ticker += inc;
}
// defaults
$scope.ticker = 0;
$scope.from = 0;
$scope.inc = 1;
$scope.times = 0;
$scope.start = function() {
counterInstance = $interval(counterFunction, 1000, $scope.times, true, $scope.from, $scope.inc);
}
/* Cancel functionality removed for brevity.. */
});
describe('calculator tests', function () {
beforeEach(module('calculatorApp'));
var $controller;
var $scope;
var $interval;
var $rootScope;
beforeEach(inject(function(_$controller_, _$rootScope_, _$interval_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$interval = _$interval_;
}));
it('should start the interval on click using defaults', function () {
var calculatorController = $controller('CalculatorController', { $scope: $scope });
$scope.start();
expect($scope.from).toBe(0);
expect($scope.inc).toBe(1);
expect($scope.ticker).toBe(0);
// advance in time by 4 seconds
$interval.flush(4000);
expect($scope.ticker).toBe(4);
});
it('should start the interval on click with user values', function () {
var calculatorController = $controller('CalculatorController', { $scope: $scope });
$scope.from = 5;
$scope.inc = 2;
$scope.times = 10;
$scope.start();
expect($scope.from).toBe(5);
expect($scope.inc).toBe(2);
expect($scope.ticker).toBe(0);
// advance in time by 1 second from call to start()
$interval.flush(1100);
expect($scope.ticker).toBe(7);
// advance in time by 2 seconds from call to start()
$interval.flush(1100);
expect($scope.ticker).toBe(9);
// this interval stops after 10 iterations, and therefore should not pass 25!
$interval.flush(10000);
expect($scope.ticker).toBe(25);
// Another example to demonstrate the point...
$interval.flush(10000);
expect($scope.ticker).toBe(25);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment