2017-03-07 12 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秒,但仍然是......是唯一的方法吗? –