Mastering Web Application

(Rick Simeone) #1
Chapter 2
say:function (name, timeout) {
$timeout(function(){
$log.info("Hello, " + name + "!");
})
}
};
});

The $timeout service is a replacement for the JavaScript setTimeout
function. Using $timeout is preferable for the purpose of deferring
actions as it is tightly integrated with the AngularJS HTML compiler
and will trigger the DOM refresh after the time is up. On top of this the
resulting code is easy to test.

Here is the test:


describe('Async Greeter test', function () {

var asyncGreeter, $timeout, $log;
beforeEach(module('async'));
beforeEach(inject(function (_asyncGreeter_, _$timeout_, _$log_) {
asyncGreeter = _asyncGreeter_;
$timeout = _$timeout_;
$log = _$log_;
}));

it('should greet the async World', function () {
asyncGreeter.say('World', 9999999999999999999);
//
$timeout.flush();
expect($log.info.logs).toContain(['Hello, World!']);
});
});

Most of this code should be easy to follow but there are two very interesting bits
that require more attention. Firstly we can see a call to the $timeout.flush()
method. This one little call on the $timeout mock simulates an asynchronous event
being triggered. The interesting part is that we've got full control over when this
event is going to be triggered. We don't need to wait for the timeout to occur, nor
are we on the mercy of external events. Please note that we've specified a very long
timeout period, yet our test will execute immediately, since we don't depend on the
JavaScript's setTimeout. Rather it is the $timeout mock that simulates the behavior
of the asynchronous environment.

Free download pdf