2016-10-09 7 views
0

私はジャスミンテストに新たなんだが、ここで私は工場で私の$資源をテストするユニットテスト、 ので、私が最初にこの工場があります。ジャスミン工場

angular.module('starter.services', []) 
 
    .factory('API', function($rootScope, $resource) { 
 
    var base = "http://192.168.178.40:8000/api"; 
 
    return { 
 
     getGuestListForH: $resource(base + '/guests/:id/:wlist', { 
 
     id: '@id', 
 
     wlist: '@wlist' 
 
     }) 
 
    } 
 
    });

と私テスト:

beforeEach(module('starter.services')); 
 
describe('service: API resource', function() { 
 
    var $scope = null; 
 
    var API = null; 
 
    var $httpBackend = null; 
 

 
    beforeEach(inject(function($rootScope, _API_, _$httpBackend_) { 
 
    $scope = $rootScope.$new(); 
 
    API = _API_; 
 
    $httpBackend = _$httpBackend_; 
 
    $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{ 
 
     id: 1, 
 
     name: 'a' 
 
    }, { 
 
     id: 2, 
 
     name: 'b' 
 
    }]); 
 
    })); 
 
    afterEach(function() { 
 
    $httpBackend.verifyNoOutstandingExpectation(); 
 
    $httpBackend.verifyNoOutstandingRequest(); 
 
    }); 
 
    it('expect all resource in API to br defined', function() { 
 
    $httpBackend.expect('http://192.168.178.40:8000/api/guests'); 
 

 
    var dd = API.getGuestListForH.query(); 
 
    expect(dd.length).toEqual(2); 
 

 
    expect(API.getGuestListForH).toHaveBeenCalled(); 
 

 
    }); 
 
});

と私は結果になった:

  • 期待0等しい2
    • 期待スパイするのではなく、機能 .Iは、工場内のリソースをテストしたい、ここで何が問題 を得ました何をするのが最善の方法ですか?

答えて

0

あなたのテストでも$rootScope、あなたがやった他のすべての変数宣言なしで行うことができます。

expecttoHaveBeenCalledの代わりに、サービスのメソッドのテストを書いているので、それを呼び出して結果が何かであると予想する必要があります。このような

何か:

describe('Service: starter.services', function() { 
    beforeEach(module('starter.services')); 
    describe('service: API resource', function() { 
     beforeEach(inject(function(_API_, _$httpBackend_) { 
      API = _API_; 
      $httpBackend = _$httpBackend_; 

      $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{ 
       id: 1, 
       name: 'a' 
      }, { 
       id: 2, 
       name: 'b' 
      }]); 
     })); 

     afterEach(function() { 
      $httpBackend.verifyNoOutstandingExpectation(); 
      $httpBackend.verifyNoOutstandingRequest(); 
     }); 

     it('expect all resource in API to br defined', function() { 
      var dd = API.getGuestListForH.query(); 
      $httpBackend.flush(); 
      expect(dd.length).toEqual(2); 
     }); 
    }); 
}); 

は、この情報がお役に立てば幸いです。

+0

お返事ありがとうございます。あなたのソリューションはうまくいきますが、サービスモジュールのリソース(id、wlist)の中のパラメタを誤って削除した場合、このテストは常に成功を返します。 。あなたはどう思いますか? –