使用Parse SDK和Karma测试角度服务的最佳解决方案

时间:2014-12-27 17:08:13

标签: angularjs parse-platform jasmine karma-jasmine

我试图自动化测试通过Parse SDK调用Parse.com的Angular服务。

我遇到的问题是承诺不会得到解决,除非我明确地触发了摘要周期,以及我的服务完成方式,我必须在我的服务实现中做到这一点,这是不可持续的。

我的服务代码如下:

factory('myService', function($http, $q, $rootScope) {

  var myService = {};

  myService.simplePromiseTest = function() {
    var p = $q.defer();
    var query = new Parse.Query("AnyObjectInParse");
    query.find().then(function(results){
      p.resolve(results);

      // *** I have to include that line for the jasmine test to run ***
      $rootScope.$apply();
    });     
    return p.promise;
  }
 }

 return myService;

}

这是我的茉莉花测试

async.it('should resolve the promise', function(done) {
  myService.simplePromiseTest().then(function(results) {
    // this is never called if don't trigger the digest from the service code
    done();
   });

   // This line is use less as when I get into that line, the promise is not resolved.
   // $scope.$root.$digest();
});

情况如下:

  • 我必须等待解析才能在触发摘要周期之前结束解析
  • 我无法找到任何其他解决方案,而不是使用此代码污染我的服务代码
  • 我想找到一个可持续的解决方案,并不要求我更新我的服务代码以通过测试。

在此先感谢我迷失了,我可能会遗漏一些明显的东西:-)

1 个答案:

答案 0 :(得分:0)

在测试本身而不是在promise实现中调用$rootScope.$apply();done的测试是异步的,因此可以在之后解决它。或者使用Angular 1.3。

一般来说,为了测试承诺,我可能会推荐mocha而不是Jasmine,因为它支持使用return语句开箱即用的承诺测试。