2

我想爲我的angularjs應用程序專門爲數據庫服務添加一些測試用例。針對數據庫服務的AngularJS單元測試

那麼問題是,我不能真正打開我的單元測試數據庫。

我的測試用例是這樣的:

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(); 
    }); 
}); 

我廠是這樣的:

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; 
    } 
    }); 
}; 

好吧,我,如果我跑因緣開始得到這個錯誤:

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) 

因緣測試瀏覽器我使用Chrome瀏覽器。

回答

1

那麼我發現,我必須在離子平臺準備好之前將數據庫保存在beforeEach中。現在看起來喜歡這個和它的工作:

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); 
    }); 
}));