2017-03-07 47 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'自行返回承諾。 Theres方式嘲笑它並且在您的測試中控制它。我建議看看。 –

回答

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秒才能發出響應,所以我可以將時間減少到2秒而不是5秒,但仍然是......是唯一的方法嗎? –