[英]Unit Testing: Karma-Jasmine not resolving Promise without implicitly calling $rootScope.$digest();
我有一个Angular
服务,该服务调用服务器并获取用户列表。 服务返回Promise
。
问题
直到并且除非我调用$rootScope.$digest();
才解决承诺$rootScope.$digest();
在服务或测试本身中。
setTimeout(function () {
rootScope.$digest();
}, 5000);
显然,调用$rootScope.$digest();
是一种解决方法,我无法在角度服务中调用它,因此我在unit test
以5秒的间隔调用它,我认为这是一个不好的做法。
请求
请为此提出一个实际的解决方案。
下面给出的是我编写的测试。
// 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;
}
您可以通过调用$timeout.flush()
来使promise刷新。 它使您的测试更加同步。
这是一个例子:
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();
});
另外:故障回复不会被处理,因此会增加测试的复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.