我有一个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方式嘲笑它并且在您的测试中控制它。我建议看看。 –