Angular unit tests - timeout, exception
Demonstrating usage of module and inject from angular mocks
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
angular.module('myApp', []).service('MyService', ['$q', '$timeout', function ($q, $timeout) {
this.foo = function () {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('resolved value');
}, 90000);
return deferred.promise;
}
}]);
T
// --- SPECS -------------------------
describe('$timeout', function () {
beforeEach(function () {
// Register module configuation code for myApp
module('myApp');
});
it("flushes timeout synchronously", inject(function (MyService, $timeout) {
var valueToVerify,
resolvedSpy = jasmine.createSpy();
// Call service under test with mock object
MyService.foo().then(resolvedSpy);
expect(resolvedSpy).not.toHaveBeenCalled();
// Timeout immediately executes function on flush()
$timeout.flush();
expect(resolvedSpy).toHaveBeenCalledWith('resolved value');
}));
it('should throw an exception when not flushed', inject(function ($timeout) {
$timeout(angular.noop);
expect(function () {
$timeout.verifyNoPendingTasks();
}).toThrow();
}));
it('should do nothing when all tasks have been flushed', inject(function ($timeout) {
$timeout(angular.noop);
$timeout.flush();
expect(function () {
$timeout.verifyNoPendingTasks();
}).not.toThrow();
}));
});
describe('$exceptionHandlerProvider and $LogProvider', function () {
it('should capture log messages and exceptions', function () {
// Mock implementation of $log gathers all logged messages in arrays
// These arrays are exposed as `logs` property of each of the
// level-specific log function
module(function ($exceptionHandlerProvider) {
// "log" mode stores an array of errors in $exceptionHandler.errors
$exceptionHandlerProvider.mode('log');
...