サーバーを呼び出してユーザーリストを取得するサービス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'はそれ自身で約束を返します。それを嘲笑し、あなたのテストでそれを制御する方法。私はそれを調べることをお勧めします。 –