2017-03-07 4 views
0

サーバーを呼び出してユーザーリストを取得するサービスAngularがあります。サービスはPromiseを返します。約束をするまで、私はサービス中またはテスト自体のいずれかで$rootScope.$digest();を呼び出さない限り、解決されていません

問題

setTimeout(function() { 
     rootScope.$digest(); 
    }, 5000); 

どうやら、$rootScope.$digest();を呼び出すと回避策だと私はので、私は、私は悪い習慣だと思う5秒の間隔でunit testでそれを呼び出していた角度サービスでそれを呼び出すことはできません。

要求

このため、実際のソリューションを提案してください。

私が書いたテストは以下の通りです。

// Before each test set our injected Users factory (_Users_) to our local Users variable 
    beforeEach(inject(function (_Users_, $rootScope) { 
     Users = _Users_; 
     rootScope = $rootScope; 
    })); 

    /// test getUserAsync function 
    describe('getting user list async', function() { 

     // A simple test to verify the method getUserAsync exists 
     it('should exist', function() { 
      expect(Users.getUserAsync).toBeDefined(); 
     }); 


     // A test to verify that calling getUserAsync() returns the array of users we hard-coded above 
     it('should return a list of users async', function (done) { 
      Users.getUserAsync().then(function (data) { 
       expect(data).toEqual(userList); 
       done(); 
      }, function (error) { 
       expect(error).toEqual(null); 
       console.log(error.statusText); 
       done(); 
      }); 

      ///WORK AROUND 
      setTimeout(function() { 
       rootScope.$digest(); 
      }, 5000); 
     }); 
    }) 

サービス

Users.getUserAsync = function() { 
    var defered = $q.defer(); 

    $http({ 
     method: 'GET', 
     url: baseUrl + '/users' 
    }).then(function (response) { 
     defered.resolve(response); 
    }, function (response) { 
     defered.reject(response); 
    }); 

    return defered.promise; 
    } 
+1

'$ http'はそれ自身で約束を返します。それを嘲笑し、あなたのテストでそれを制御する方法。私はそれを調べることをお勧めします。 –

答えて

0

あなたは約束は$timeout.flush()を呼び出してフラッシュすることがあります。これはあなたのテストを少し同期させます。

はここに例を示します

it('should return a list of users async', function (done) { 
     Users.getUserAsync().then(function (data) { 
      expect(data).toEqual(userList); 
      done(); 
     }, function (error) { 
      expect(error).toEqual(null); 
      console.log(error.statusText); 
      done(); 
     }); 

     $timeout.flush(); 
    }); 

を脇:それはテストに追加の複雑さを加えるので、フェイルバックが処理されません。

+0

恩赦はありますが、それは少し詳しく説明できますか? –

+0

@VikasBansalあなたは何を知りたいですか? –

+0

すべてのAPI呼び出しで、私は 'setTimeout'を呼び出しています。私は12以上のAPIをテストしています。だから、少し待たなければならない。 APIのほとんどが応答を送信するのに2秒かかるので、5秒ではなく2秒に短縮することができますが、それでも唯一の方法ですか? –

関連する問題