Using mocks with Jasmine tests for AngularJS

I’m not entirely sure I understand exactly what is going on here or how this is working, but posting to refer back to later.

I have a controller that’s using $interval. Rather than coding a delay into my test in order to let time pass in real time before I do my assertions, a better approach would be to mock out $interval so you can move elapsed time forward programmatically, which is a much better approach.

Luckily the ngMock package provides mocks for most things, including $interval. To move time, you call $interval.flush(millis);

[code language=”javascript”]

describe(‘Test variable date timer’, function () {

it(‘Runs for 1 iteration, 30min interval, adds 30 mins’, function () {
var $scope = {};
angular.mock.inject(function ($controller, _$interval_) {
$interval = _$interval_;
controller = $controller(‘VariableRateDateCtrl’, {$scope: $scope, $interval: $interval});


$scope.iterations = 1;
$scope.timeInterval = 30;
$ = moment();
startDate = $;

$interval.flush(1000 * $scope.iterations);

endDate = $;
expectedEndDate = startDate.clone().add($scope.timeInterval, ‘minutes’);