【发布时间】:2014-09-04 04:00:59
【问题描述】:
Angulars 内置于 $q 承诺实现使我很难在我的 Jasmine 测试环境中创建测试。我构建了一个简单的服务,其唯一目的是打开 IndexedDB 数据库:
var myApp = angular.module('myApp', []);
myApp.service('idb', function ($q) {
var dbName = 'TestDb';
this.open = function () {
var deferred = $q.defer();
var request = indexedDB.open(dbName, 1);
request.onsuccess = function () {
deferred.resolve();
};
request.onerror = function () {
deferred.reject();
};
return deferred.promise;
};
});
这是我在 Jasmine 中的测试:
describe('indexed db test', function () {
var idbOpened = false;
var idb, $rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function (_idb_, _$rootScope_) {
idb = _idb_;
$rootScope = _$rootScope_;
}));
beforeEach(function (done) {
idb.open().then(
function () {
idbOpened = true;
},
function () {
idbOpened = false;
})['finally'](done);
$rootScope.$digest();
});
it('checks if indexeddb is opened', function () {
expect(idbOpened).toBeTruthy();
});
});
你可以找到a jsfiddle here
测试失败并超时,因为 finally 的异步回调没有被调用。
我知道我必须在 promise 解决后调用 $rootScope.$digest(),因为 Angular 将 promise.resolve 回调放在 evalAsync 队列中。
我不明白如何在我的测试环境中做到这一点。显然,我如何称呼它不是要走的路。
【问题讨论】:
标签: javascript angularjs jasmine promise indexeddb