dimanche 27 septembre 2015

Angular window.openDatabase mock for jasmine

I have an angular phonegap app that I want to expand to use the window.openDatabase to access the local mobile database.

I am trying to unit test the code that creates/opens the database and I am running in to some problems.

I have a factory:

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

As well as a jasmine test:

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

And when run I get the error:

    ERROR [PhantomJS 1.9.8 (Linux 0.0.0) | localStore | openDatabase]: TypeError: 'undefined' is not an object (evaluating '_db.transaction')
    at _initialise (http://ift.tt/1WsaqEV)
    at http://ift.tt/1iV9ZVy

Can anyone see why _db is undefined following the call to $window.openDatabase?

Aucun commentaire:

Enregistrer un commentaire