我有一个测试服务的测试用例,并成功检查了我的测试用例中是否调用了get请求:
var $httpBackend, Entry, Common;
beforeEach(module('contact_journal'));
beforeEach(inject(function($injector, _Entry_,_Common_,_$state_) {
$httpBackend = $injector.get('$httpBackend');
Entry = _Entry_;
Common = _Common_;
//$httpBackend.whenGET(URLS.entry_show_path+'?id=0').respond(200,{});
// this is required to stub ui-router cycle on $http request
state = _$state_;
spyOn(state,'go');
spyOn(state,'transitionTo');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('getEntry', function(){
it('should sent GET request', function() {
$httpBackend.expectGET(URLS.entry_show_path+'?id=0').respond(200,{});
var result = Entry.getEntry(0);
$httpBackend.flush();
console.log('After flush');
console.log(result);
expect(result).toEqual({});
});
});
现在我希望结果变量具有服务的响应,以便我可以检查响应代码是200.但是,由于我之后已经完成了httpBackend flush,因此在成功执行callBack之后我无法获得结果成功给了我一个承诺。 如何从Entry.getEntry服务调用中获取结果?以下是我的服务方法:
entryService.getEntry = function(entry_id) {
show_page_loader();
return $http.get(URLS.entry_show_path, {params: { id: entry_id }})
.success(function(result){
console.log('In success');
console.log(result);
return result;
})
.error(function(data){
console.log('In error');
Common.common_flash_error_message();
console.log('error completed');
});
};
感谢您的帮助。
答案 0 :(得分:1)
由于返回值是一个承诺,您需要在单元测试时处理它。以下是如何做到这一点:
it('should sent GET request', function() {
$httpBackend.expectGET(URLS.entry_show_path+'?id=0').respond(200,{});
var result;
Entry.getEntry(0).then(function(data) {
result=data;
})
$httpBackend.flush();
console.log('After flush');
console.log(result);
expect(result).toEqual({});
});