2013-06-20 7 views
5

編集:質問をした後、私は今これを編集して私の所見を詳述しています。templateUrlとcontrollersを使用するディレクティブをテストするにはどうすればよいですか?

私のアプリはディレクティブを使用してモジュール化されています。私は、(1)独自のスコープを作成し、(2)templateUrlを使用し、(3)コントローラーでロジックとサーバーのデータをほとんどフェッチするように指示を書いています。

質問はカルマとモカを使ってユニットテストする方法です。

答えて

7

各ディレクティブごとにテストが作成されます。このディレクティブはtemplateUrlを使用しているので、html2jsを使用しました。 htmlキーはモジュールとしてインクルードする必要があります。これはtemplateCacheにテンプレートを置きます。

次に、この指示文をコンパイルして、rootScopeでリンク機能を実行しました。私はテンプレートをhtmlにすることに問題がありました。$ digestを使って解決しました。データバインディングの問題があり、理解によって解決されました。すべては以下の通りです。以下

コード、

指令:

angular.module('myApp') 
.directive('productThumb', function(){ 
    return { 
    restrict: 'AE', 
    scope: true, 
    templateUrl: 'partials/directives/product-thumb.html', 
    // controller does most of the work 
    controller: ProductThumbController 

    } 
}) ; 

describe("Unit: Testing Directives", function() { 
var elm, scope, linkFn; 
beforeEach(
    module('ogApp','partials/directives/product-thumb.html') // puts product-thumb.html 
                  // into templateCache 
); 


beforeEach(inject(function($rootScope, $compile) { 
    elm = angular.element('<product-thumb></product-thumb>'); 
    scope = $rootScope; 
    linkFn = $compile(elm); 
    scope.$digest(); // have to digest to bring html from templateCache 
    console.log('post compile',elm.html());// <== the html here still have {{}} 
})); 

it('should show a thumb',function() { 
    inject(function($controller) { 
     linkFn(scope); // <== this will create a new scope (since our directive creates 
         // new scope), runs the controller with it, and bind 
         // the element to that new scope 
     scope.$digest(); 
     console.log('post link',elm.html());// <== the html is bound 

     // inject test data (controller sets up an $on handler for addProductData event) 
     scope.$broadcast('addProductData',{title:"TEST DISPLAY NAME", 
              productId: "123", mainImageUrl: "TEST.JPG"}); 
     scope.$digest(); 
     expect(elm.find('H5').text()).to.equal("TEST DISPLAY NAME"); // <=== success 
    }); 
}); 
+1

ねえLIORは、私が言いたい、ありがとうございました。私はテンプレートの代わりにtemplateUrlを使用してangular.js指示文をテストしようとしていました。実際のテンプレートを打つのを避けようとしていました。私はあなたの答えの非常に似た変種を使用しました、違いは私がhtml2jsを使わなかったことだけです;代わりに$ templateCacheを注入して文字列を返すようにしました。もう一度、ありがとう! – yanhan

+0

私がこれを持っているのは、部分テンプレートの場所です。あなたはどのパスを使うべきか、どのように知ることができますか? –

+0

パスはアプリケーションルートからの相対パスです。メインの 'app.js'が存在します。 – demisx

関連する問題