用于jasmine的Angular window.openDatabase模拟

时间:2015-09-28 01:14:47

标签: angularjs cordova unit-testing jasmine

我有一个有角度的phonegap应用程序,我想扩展它以使用window.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

在调用$ window.openDatabase后,有人能看到为什么_db未定义?

更新:

问题是间谍。如果我删除mockspy = spyOn($ window,'openDatabase');并更改测试以访问模拟函数内的布尔变量集,一切正常工作!

1 个答案:

答案 0 :(得分:1)

更新:

问题是间谍。如果我删除mockspy = spyOn($window, 'openDatabase');并更改测试以访问模拟函数内的布尔变量集,那么一切都按照正常情况工作!