Angulars build in $q promise implementation makes it hard for me to create tests in my Jasmine testing environment. I build a simple service which only purpose is to open an IndexedDB database:
var myApp = angular.module('myApp', []);
myApp.service('idb', function ($q) {
var dbName = 'TestDb';
this.open = function () {
var deferred = $q.defer();
var request = indexedDB.open(dbName, 1);
request.onsuccess = function () {
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise;
};
});
Here is my test in Jasmine:
describe('indexed db test', function () {
var idbOpened = false;
var idb, $rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function (_idb_, _$rootScope_) {
idb = _idb_;
$rootScope = _$rootScope_;
}));
beforeEach(function (done) {
idb.open().then(
function () {
idbOpened = true;
},
function () {
idbOpened = false;
})['finally'](done);
$rootScope.$digest();
});
it('checks if indexeddb is opened', function () {
expect(idbOpened).toBeTruthy();
});
});
You can find a jsfiddle here
The test fails with a timeout because the asynchronous callback for finally is not invoked.
I understand I have to call $rootScope.$digest() after the promise is resolved because Angular puts the promise.resolve callbacks on the evalAsync queue.
What I don't understand is how I can do this in my Testing environment. Obviously how I'm calling it is not the way to go.