ダイジェストを強制する $scope がない場合、AngularJS、Jasmine 2.0 で Promise を解決するにはどうすればよいでしょうか? 質問する

ダイジェストを強制する $scope がない場合、AngularJS、Jasmine 2.0 で Promise を解決するにはどうすればよいでしょうか? 質問する

約束はAngular/Jasmineテストでは、強制しない限り解決されません。$scope.$digest()これは馬鹿げていると思いますが、問題ありません。該当する場合は(コントローラー)動作しています。

私が今直面している状況は、アプリケーション内のスコープをあまり気にしないサービスがあり、サーバーからデータを返すだけで、Promise が解決されていないように見えることです。

app.service('myService', function($q) {
  return {
    getSomething: function() {
      var deferred = $q.defer();
      deferred.resolve('test');
      return deferred.promise;
    }
  }
});

describe('Method: getSomething', function() {
  // In this case the expect()s are never executed
  it('should get something', function(done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
      expect(1).toEqual(2);
    });

    done();
  });

  // This throws an error because done() is never called.
  // Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  it('should get something', function(done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
      expect(1).toEqual(2);
      done();
    });
  });
});

この機能をテストする正しい方法は何ですか?

編集: 参考のための解決策。どうやら、サービスが $rootScope を使用していない場合でも、$rootScope を強制的に挿入してダイジェストする必要があるようです。

  it('should get something', function($rootScope, done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
    });

    $rootScope.$digest();
    done();
  }); 

ベストアンサー1

$rootScopeテストに挿入してトリガーする必要があります$digest

おすすめ記事