【问题标题】:Ionic Jasmin test: $scope.$digest() not resolving promise离子茉莉花测试:$scope.$digest() 没有解决承诺
【发布时间】:2017-01-06 01:40:16
【问题描述】:

我有以下服务,为了解决这个问题,我现在保持简单:

angular.module('handheld')
.factory('database', ['$ionicPlatform', '$cordovaSQLite', 
    function ($ionicPlatform, $cordovaSQLite) {

    return {
        insert: function(table, attributes) {
            return $cordovaSQLite.execute({}, 'query', []);
        }   
    };

}]);

下面的测试模拟 $cordovaSQLite.execute 以返回一个承诺:

describe('database', function() {

  var database, $scope;

  beforeEach(function() {
    module('handheld');

    module(function($provide, $urlRouterProvider) {
      $provide.value('$ionicTemplateCache', function(){});
      $urlRouterProvider.deferIntercept();  

      $provide.service('$cordovaSQLite', function($q) {
        this.execute = jasmine.createSpy('execute').and.callFake(function(db, query, values) {
          return $q.when(true);
        });
      });
    });
  });

  beforeEach(inject(function($injector) {
    database = $injector.get('database');
    $scope = $injector.get('$rootScope').$new();
  }));

  describe("when inserting", function() { 
    var result;

    beforeEach(function(done) {
      database.insert('table', {}).then(
        function(success){
          result = success;
          done();
        },
        function(err){
          result = err;
          done();
        }
      );
    });

    it("should be successful", function() { 
      $scope.$digest();
      expect(result).toEqual(true);
    });
  });
});

我关注了this link(点Mocking Methods Returning Promises

还有this other link(点禁用$ionicTemplateCache

但仍然收到错误超时 - 在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时内未调用异步回调。(请注意,我正在调用 $scope.$digest(); 已经)

我想提一下,模拟工作正常,因为我可以在 return $q.when(true); 处放置断点并从那里进行跟踪,因此服务是调用模拟版本。

我尝试在这个网站和互联网的其他地方进行搜索,但找不到任何令人满意的解决方案,因为在我看来,我正在做每个人都在做的事情。

任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs ionic-framework jasmine promise


    【解决方案1】:

    我终于找到了问题所在。使用 Angular,我们不需要将嵌套的 beforeEachdone() 回调一起使用,因为 $scope.$digest 会阻塞和解析承诺,所以我们可以将断言放在后面。

    link

    嵌套的描述块应该是这样的:

    describe("when inserting", function() { 
    
        it("should be successful", function() {
          var result;
    
          database.insert('table', {}).then(
            function(success){
              result = success;
            },
            function(err){
              result = err;
            }
          );
    
          $scope.$digest();
          expect(result).toEqual(true);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 2023-03-27
      • 1970-01-01
      • 2017-12-21
      • 2021-05-25
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      相关资源
      最近更新 更多