Ionic Jasmin测试:$ scope。$ digest()不解决承诺

时间:2017-01-05 16:38:51

标签: angularjs ionic-framework jasmine promise

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

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(点模拟方法返回承诺

还有this other link(点禁用$ ionicTemplateCache

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

我想提一下,模拟工作正常,因为我能够在返回$ q.when(true); 并从那里追踪断点,所以服务正在调用模拟版本。

我试图在这个网站和互联网的其余部分进行搜索,但无法找到任何令人满意的解决方案,因为在我看来,我正在做每个人所做的事情。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我终于发现了什么是错的。使用Angular,我们不需要使用嵌套的 beforeEach 完成()回调,因为 $ scope。$ digest 会阻止并解析承诺所以我们可以把断言放在后面。

请参阅link

以下是嵌套的describe块应该如何:

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);
    });
});
相关问题