2016-03-21 4 views
0

おはよう、工場でのメソッドのパラメータをテストする

私はAngularJSの工場で定義されたメソッドのいくつかのフィールドの値をテストしようとしています。

私のコードは次のとおりです:

'use strict'; 
 

 
services.factory('toto', ['$resource', function ($resource) { 
 
    return $resource('abc', 
 
     {}, 
 
     { 
 
      method1: { 
 
       method: 'POST', 
 
       url: 'urlXYZ' 
 
      } 
 
     }) 
 
}]);

私は法1における方法とURLの値をチェックしたいと思います。

私は多くのことを試してみましたが、どれもOKではありません:

beforeEach(function(){ 
 
    module('myApp'); 
 
}); 
 

 
describe('tests', function() { 
 
    var toto; 
 

 
    beforeEach(function() { 
 
     inject(function (_toto_) { 
 
      toto = _toto_; 
 
     }); 
 
    }); 
 

 
    // check to see if it has the expected function 
 
    describe('toto service has the expected properties', function() { 
 

 
     it('should have a method1 function', function() { 
 
      expect(angular.isFunction(toto.method1)).toBe(true); 
 
     }); 
 

 
     it('should have a method1 function with the field method defined', function() { 
 
      expect(toto.method1.url).toBeDefined(); 
 
     }); 
 

 
    }); 
 

 
});

それが唯一の "定義する未定義の期待。" と私に言います2回目のテストのために。

あなたは私が望んでいることをどうやって管理できるか考えていますか?

編集:私は非常にわかりやすいとは確信していません... 誰かが間違ってそれらを変更しないかどうかを知るために、method1のurlとメソッドのパラメータの値をチェックします。

編集2:ここではqwettyの助けを借りて解決策があります。試験で

it('should perform POST request to the expected url', function() { 
 
      $httpBackend 
 
       .expectPOST('the expected url') 
 
       .respond({}); 
 
      toto.paginate(); 
 
      $httpBackend.flush(); 
 

 
     });

答えて

1

私はあなたの$のリソースファクトリに定義されている "追加" メソッドを呼び出します。

it('should perform POST request and method should be available', function() { 
    $httpBackend 
      .expectPOST('some expected url') 
      .respond({}); // does not matter what You return here ... 
    toto.method1(); 

}); 
+0

あなたのソリューションは動作しますが、私が望むやり方ではありません...私はパラメータのURLとメソッドの値をチェックしたいと思います。あなたのソリューションでは、私は 'expectPOST'の代わりに 'expectGET'メソッドを使うこともできますが、テストはOKです。 – Marine

+0

テストでは、メソッド 'method1'のパラメータ' url'のチェック値を書きました。 – qwetty

+0

CD .. パラメータurlの(将来)値を変更すると、テストは失敗します。同じことがメソッド名に適用されます。別の名前はリクエストを実行せず、 'expectPOST'はマッチせず、エラーが発生します。したがって、urlとmethodの両方は、単一/小/可読テストで完全にテストされています。 – qwetty

0

あなたが見ることができるようにあなたが$resource()で定義されているように、リソースオブジェクトのメソッドtoto.method1は機能ではなく、オブジェクトです。

私はあなたがもちろん工場

services.factory('toto', ['$resource', function ($resource) { 
    var action = { 
     method1: { 
      method: 'POST', 
      url: 'urlXYZ' 
     } 
    }; 
    return { 
     resource: $resource('abc',{}, action), 
     action: action 
    }; 
}]); 

のリターンを変更することができると思い、あなたも、あなたが工場を使用する方法を変更する必要があります。

または使用defineProperty:それはちょうど、テスト目的のためにあまりにも多くの努力を思われるが

services.factory('toto', ['$resource', function ($resource) { 
    var action = { 
     method1: { 
      method: 'POST', 
      url: 'urlXYZ' 
     } 
    }; 
    var resource = $resource('abc',{}, action); 
    Object.defineProperty(resource, 'method1', { 
     value: action.method1 
    }); 
    return resource; 
}]); 

。 :)

関連する問題