【问题标题】:AngularJS unit tests for database service用于数据库服务的 AngularJS 单元测试
【发布时间】:2016-02-17 15:26:27
【问题描述】:

我想为我的 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 浏览器。

【问题讨论】:

    标签: angularjs unit-testing ionic-framework karma-runner karma-jasmine


    【解决方案1】:

    好吧,我发现我必须在 ionicPlatform 准备好之后将数据库保存在 beforeEach 中。现在它看起来像这样并且它的工作原理:

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

    【讨论】:

      猜你喜欢
      • 2016-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      相关资源
      最近更新 更多