我與因緣/茉莉花測試框架的角度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()方法。總是在回調和期望值之間沖洗 –
感謝您請檢查我更新的問題 –