1
我有一個角phonegap應用程序,我想展開使用window.openDatabase訪問本地移動數據庫。Angular window.open數據庫模擬茉莉花
我想單元測試創建/打開數據庫的代碼,我遇到了一些問題。
我有一個工廠:
'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');並更改測試以訪問模擬函數內部的布爾變量集,一切正常!
請使用您問題上的編輯鏈接添加其他信息。後回答按鈕應該只用於問題的完整答案。 –
我添加的附加信息解決了問題。它應該仍然不是答案嗎? – user2521816