Skip to content

Instantly share code, notes, and snippets.

@RhinoLance
Last active August 29, 2015 14:20
Show Gist options
  • Save RhinoLance/6b36e319b1f371150fdd to your computer and use it in GitHub Desktop.
Save RhinoLance/6b36e319b1f371150fdd to your computer and use it in GitHub Desktop.
Angular and Jasmine testing withservice using $q
angular.module('MyModule', [])
// DB wrapper
.factory('rsDb', function($q, DB_DEFINITION) {
var self = this;
self.db = null;
self.init = function() {
self.db = window.openDatabase(DB_DEFINITION.name, '1.0', 'database', -1);
var promises = [];
angular.forEach(DB_DEFINITION.tables, function(table) {
self.query( table.create)
.then(function(){
console.log("Create table promise resolved.");
angular.forEach( table.indexes, function(sql){
promises.push( self.query(sql));
console.log("Added index promise");
});
angular.forEach( table.alter, function(sql){
promises.push( self.query(sql));
console.log("Added alter promise");
});
});
});
return $q.all(promises)
.then(function() {
console.log("Tables should all have been created now ++++++++++++++++++++++++++++++");
});
};
self.query = function(query, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function(transaction) {
transaction.executeSql(query, bindings, function(transaction, result) {
console.log('db.query: ' + query + '\n' + JSON.stringify(bindings));
var aResultSet = [];
for (var cI = 0; cI < result.rows.length; cI++) {
//console.log(JSON.stringify(result.rows.item(cI)));
aResultSet.push(result.rows.item(cI));
}
console.log('db.query resolved');
deferred.resolve(aResultSet);
}, function(transaction, error) {
console.log('db.query rejected: ' + JSON.stringify(transaction) + '\n' + JSON.stringify(error));
deferred.reject(error);
});
});
return deferred.promise;
};
self.removeAll = function() {
var promises = [];
angular.forEach(DB_DEFINITION.tables, function(table) {
promises.push( self.query( 'DROP TABLE ?', table.name));
});
return $q.all(promises);
};
self.reset = function() {
return self.removeAll()
.then(self.init());
};
return self;
})
.constant('DB_DEFINITION', {
name: 'mydb',
tables: [
{
name: 'Attachments',
create: 'CREATE TABLE IF NOT EXISTS Attachments(' +
' AttachmentId INTEGER PRIMARY KEY, ' +
' InspectionId INTEGER, ' +
' ModuleId TEXT, ' +
' Comment TEXT, ' +
' Data TEXT, ' +
' RequiresSync INTEGER, ' +
' Created INTEGER, ' +
' ServerModified INTEGER, ' +
' FileIsLocal INTEGER ' +
');',
alter: [
'ALTER TABLE Attachments ADD COLUMN ServerModified INTEGER DEFAULT -1', //Added v1.9
'ALTER TABLE Attachments ADD COLUMN FileIsLocal INTEGER DEFAULT 0,', //Added v1.9
'ALTER TABLE Attachments ADD COLUMN Created INTEGER DEFAULT 0' //Added v1.9
],
indexes: [
'CREATE INDEX IF NOT EXISTS ix_Attachments_InspectionId ON Attachments( InspectionId );',
'CREATE INDEX IF NOT EXISTS ix_Attachments_RequiresSync ON Attachments( RequiresSync );'
]
},
{
name: 'Settings',
create: 'CREATE TABLE IF NOT EXISTS Settings(' +
' Key TEXT PRIMARY KEY, ' +
' Value TEXT ' +
');',
alter: [],
indexes: [
'CREATE INDEX IF NOT EXISTS ix_Settings_Key ON Settings( Key );'
]
}
]
}),
.factory('rsSettings', function(rsDb, $q) {
var self = this;
self.all = function() {
return rsDb.query('SELECT * FROM Settings');
};
self.get = function(id) {
var defer = $q.defer();
rsDb.query('SELECT * FROM Settings WHERE Key = ?', [id])
.then(function(result){
if( result.length > 0 ){
defer.resolve(JSON.parse(result[0]));
}
else{
defer.reject( {code: -1, message: 'Record not found'});
}
});
return defer.promise;
};
self.save = function(key, value){
var jValue = JSON.stringify(value);
return self.get(key)
.then(rsDb.query( 'UPDATE Settings SET Value = ? WHERE Key = ?', [jValue, key]))
.catch(rsDb.query( 'INSERT INTO Settings (Key, Value) VALUES (?, ?)', [key, jValue]));
};
self.delete = function(key){
return rsDb.query( 'DELETE FROM Settings WHERE Key = ?', [key]);
};
return self;
});
/*global describe, module, beforeEach, inject, it, expect, fail */
describe('Testing the service: settingService', function() {
'use strict';
beforeEach(module('MyModule'));
var rsSettings,
rsDb;
beforeEach(inject(function (_rsSettings_, _rsDb_) {
rsSettings = _rsSettings_,
rsDb = _rsDb_
;
}));
describe( 'Adding and removing a setting', function() {
var tests = {Newton: {key: 'Newton', value: 'apple'}};
var results = {};
beforeEach(function(done){
inject(function($rootScope) {
rsDb.init()
.then(function () {
console.log("Tables should all have been created now ---------------");
return rsSettings.save('Newton', 'apple');
})
.then(function(){
return rsSettings.get('Newton');
})
.then(function (value) {
results.Newton = value;
console.log('*********************** ' + value);
})
.finally(done);
$rootScope.$digest();
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment