我有一个有棱角的phonegap应用程序,我想展开它来使用窗口。openDatabase访问本地移动数据库
我正试图对创建/打开数据库的代码进行单元测试,我遇到了一些问题。
我有一个工厂:
'use strict';
angular.module('data')
.factory('localStore', ['$window',
function ($window){
var _db;
function _populate(tx){
tx.executeSQL('CREATE TABLE IF NOT EXISTS TEST(id unique, description)');
}
function _error(err){
console.log('Error populating DB: ' + err.code);
}
function _success(){
console.log('DB populate successful');
}
function _initialise(){
if ('undefined' === typeof _db){
_db = $window.openDatabase("Database", "1.0", "My App", 100000);
_db.transaction(_populate, _error, _success);
}
}
return {initialise: _initialise};
}]);
以及茉莉测试:
'use strict';
describe('localStore', function() {
var localStore, $window, txnspy, mockspy;
beforeEach(module('data'));
beforeEach(function(){
txnspy = jasmine.createSpy('spy');
inject(function(_localStore_, _$window_){
localStore = _localStore_;
$window = _$window_;
$window.openDatabase =
function(db, version, name, size){
// throw(new Error('Local open'));
return {
transaction: function(txnFn){
txnFn({executeSql: txnspy});
}
};
};
mockspy = spyOn($window, 'openDatabase');
});
});
it('initialise defined', function(){
expect(localStore.initialise).toBeDefined();
});
it('openDatabase', function(){
localStore.initialise();
expect(mockspy).toHaveBeenCalled();
expect(txnspy).toHaveBeenCalled();
expect(txnspy.calls.first().args[0]).toMatch(/^CREATE TABLE IF NOT EXISTS/);
});
});
当运行时,我得到错误:
ERROR [PhantomJS 1.9.8 (Linux 0.0.0) | localStore | openDatabase]: TypeError: 'undefined' is not an object (evaluating '_db.transaction')
at _initialise (http://0.0.0.0:8081/base/app/scripts/data/localStore.js?15494938407287b8b9ee539800f7a42ae33c9b79:9)
at http://0.0.0.0:8081/base/test/spec/data/localStore.js?7bcca70e4f2dd2473ec1ddb5d521f37ac7f4b423:43
有没有人知道为什么_db在调用$window.openDatabase后是未定义的?
更新:问题是间谍。如果我删除mockspy = spyOn($window, 'openDatabase');并更改测试以访问模拟函数内的布尔变量集,一切正常工作!
UPDATE:
问题是间谍。如果我删除mockspy = spyOn($window, 'openDatabase');
并更改测试以访问模拟函数内的布尔变量集,则一切正常工作!