我想为我的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;
}
});
};
如果我运行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)
作为业力测试浏览器,我使用Chrome浏览器。
答案 0 :(得分:1)
我发现在ionicPlatform准备好之后我必须在beforeEach中保存db。现在它看起来像这样及其工作:
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);
});
}));