首页 > 解决方案 > AngularJS,Karma:无法获得 indexedDB 包装器的承诺解决工作

问题描述

我正在使用localforage并有一个 angularjs 包装器来获取项目并给出一个承诺对象

工厂.js

service.prototype.getItem = function getItem(key) {
   var deferred = $q.defer();
   localforage.getItem(key).then(function (item) {
     //some calculations
     deferred.resolve(item);
   }
   return deferred.promise;
}

工厂.spec.js

it('should get item', function (done) {
   mocks.inject(function ($rootScope, $httpBackend, service) {
      service.getItem('test').then(function(item) {
         expect(item).toBe('some value');
         done();
      });
      $rootScope.$digest();
   });
}

在上面的代码中,服务回调被正确触发并获取值。但无法在 spec.js 中触发回调

标签: angularjsjasminekarma-runnerlocalforage

解决方案


找不到你处理的地方localforage?我想测试的目的是检查一些重要的计算,那么你应该这样做

it('should get item', function () {
    spyOn(localforage, 'getItem').and.returnValue($q.resolve(item));

    service.getItem('test').then(function(responseAfterCalculations) {
         expect(responseAfterCalculations).toBe('some value');
    });
    $rootScope.$digest();
}

基本上,方法在 repo 中localforage.getItem有自己的测试。在单元测试中,您只需测试自己的功能和 3rd 方服务实现。所以这里最好的方法是简单地模拟localforage. 如果您想要更完整的测试,您需要一种 e2e 方法,例如基于量角器。


推荐阅读