Kingalione Kingalione - 4 months ago 20
AngularJS Question

AngularJS unit tests for database service

I want to add some test cases for my angularjs application specially for the database service.

Well the problem is that I can't really open the database in my unit test.

My testcase looks like this:

describe("DatabaseCreateService‚", function () {
var DatabaseCreateService,cordovaSQLite;

beforeEach(module("starter.services"));
beforeEach(module("ngCordova"));
beforeEach(module("ionic"));

beforeEach(inject(function (_DatabaseCreateService_, $cordovaSQLite) {
DatabaseCreateService = _DatabaseCreateService_;
cordovaSQLite = $cordovaSQLite;
}));

it("should create the table cg_local_values", function () {
var db = DatabaseCreateService.initDB("Test.db");
expect(db).toBeDefined();
});
});


My factory looks like this:

var initDB = function(dbName) {
$ionicPlatform.ready(function() {
if (window.cordova) {
db = $cordovaSQLite.openDB(dbName);
return db;
}else{

db = window.openDatabase(dbName, '1', 'my', 1024 * 1024 * 100);
console.log(JSON.stringify(db));
return db;
}
});
};


Well I get this error if I run karma start:

Expected undefined to be defined.
at Object.<anonymous> (pathToTests/tests/services/DatabaseServiceTest.js:42:16)
Chrome 46.0.2490 (Mac OS X 10.11.1): Executed 24 of 24 (1 FAILED) (0.183 secs / 0.146 secs)


As karma test browser I use the Chrome browser.

Answer

Well I found out that I have to save the db in beforeEach after ionicPlatform is ready. Now it looks likes this and its working:

var DatabaseCreateService,cordovaSQLite,ionicPlatform,rootScope,q; var db=null;

beforeEach(module("starter.services"));
beforeEach(module("ngCordova"));
beforeEach(module("ionic"));

beforeEach(inject(function (_DatabaseCreateService_, $cordovaSQLite,$ionicPlatform,$rootScope,$q) {
  DatabaseCreateService = _DatabaseCreateService_;
  cordovaSQLite = $cordovaSQLite;
  ionicPlatform = $ionicPlatform;
  q = $q;
  rootScope = $rootScope;

  ionicPlatform.ready(function() {
    db = window.openDatabase("Test.db", '1', 'my', 1024 * 1024 * 100);
  });
}));