我有一個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;
}
'$ http'自行返回承諾。 Theres方式嘲笑它並且在您的測試中控制它。我建議看看。 –