您好,我想为我的 ionic 框架应用程序实现一些测试用例,该应用程序使用 cordova sqliteplugin 从 sqlite 数据库获取数据。
我在为 angularjs 编写测试用例方面非常陌生。
我的目标是测试我的服务是否有数据。
那么在我的 app.js 中,我用这个打开数据库:
angular.module('starter', ['ionic','starter.services', 'starter.controllers', 'starter.config','ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite, $ionicLoading) {
$ionicPlatform.ready(function() {
var dbName = 'testDB.db';
if(window.cordova) {
window.plugins.sqlDB.copy(dbName);
db = $cordovaSQLite.openDB(dbName);
}
....
我的 services.js 看起来像这样:
angular.module('starter.services', ['ngCordova'])
.factory('ProductService',function($cordovaSQLite){
var getAllProducts = function() {
var productList = [];
var query = "SELECT c.name as name, c.id as id FROM cars as c ORDER BY c.name";
$cordovaSQLite.execute(db, query, []).then(function(res) {
if(res.rows.length > 0) {
for(var i = 0; i < res.rows.length; i++) {
productList.push({id: res.rows.item(i).id, name: res.rows.item(i).name});
}
}
}, function (err) {
console.error(err);
});
return productList;
};
return {
getAllProducts: getAllProducts
};
});
我测试服务的测试描述如下所示:
describe('ProductService unit tests', function () {
var ProductService;
beforeEach(module('starter.services'));
beforeEach(angular.mock.module('starter'));
beforeEach(inject(function(_ProductService_) {
ProductService = _ProductService_;
}));
it('can get an instance', inject(function(ProductService) {
expect(ProductService).toBeDefined();
}));
//THIS TEST FAILS
it('should get some products from the database', inject(function(ProductService) {
expect(ProductService.getAllProducts().length).toBeGreaterThan(0);
}));
});
如果我运行测试,我会得到:
TypeError: 'null' is not an object (evaluating 'n.transaction')
我认为这是因为数据库在测试期间没有真正初始化,所以我尝试模拟启动应用程序但它没有解决问题。我试图用谷歌搜索,但找不到任何使用 sqlite 和 angularjs 的 karma 示例或教程。
谢谢你的帮助。