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 であることを確認できるように、結果変数にサービスの応答を含めたいと思います。約束。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

戻り値は promise であるため、単体テスト中に処理する必要があります。これを行う方法は次のとおりです。

 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 に答える