0

我有一个测试服务的测试用例,并成功检查了我的测试用例中是否调用了 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 刷新之后,我无法在成功 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');
      });
  };

谢谢你的帮助。

4

1 回答 1

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({});
    });
于 2015-02-17T09:37:25.343 回答