我与因缘/茉莉花测试框架的角度JS应用程序的工作角度的单元测试工厂,我需要测试工厂,返回一个HTTP承诺,但它总是返回undefined使用HTTP请求
这里是我厂
angular.module('GithubUsers').factory('Users',['$http','$q',function($http,$q){
return{
getAllUsers:function(){
var defered= $q.defer();
$http({
url:'https://api.github.com/users',
method:'GET'
}).then(function(users){
defered.resolve(users.data);
},function(err){
defered.reject(err);
})
return defered.promise;
}
}
}])
这里是我的测试
更新感谢您的回答我修改了代码以下,但没有我得到这个错误
可能未处理的拒绝:{“地位”:0,“配置”:{“方法”:“GET”,” transformRequest“:[null],”transformResponse“:[null],”jsonpCallbackParam“:”callback“,”url“:”https://api.github.com/users?since=1“,”headers“:{”Accept“:”application/json,text/plain,/ “},” 缓存 “:假},” 状态文本 “:”“}抛出
describe('Test Users Factory',function(){
var $controller,
Users,
$rootScope,
$httpBackend,
$q;
beforeEach(module('GithubUsers'));
beforeEach(inject(function(_$controller_,_Users_,_$rootScope_,_$httpBackend_,_$q_){
$controller = _$controller_;
Users = _Users_;
$rootScope= _$rootScope_;
$httpBackend=_$httpBackend_;
}))
it('should get users',function(){
var result;
$httpBackend.whenGET('https://api.github.com/users?since=1').respond(function(){
return {data:[{id:2}],status:200};
})
Users.getAllUsers().then(function(res){
result = res;
});
$httpBackend.flush();
$rootScope.$digest()
expect(result).toBeTruthy();
})
})
在此先感谢!
感谢您的回复,但不幸的是它没有为我工作 –
确实忘了添加flush()方法。总是在回调和期望值之间冲洗 –
感谢您请检查我更新的问题 –