2013-05-03 13 views
6

My <custom-directive>replace:truetemplate: '<img />'です。 ユニットテストを書くにはどうしたらいいですか?実際にはimgでカスタムディレクティブを置き換えることをテストしたいと思う。Replaceをtrueに設定した指令をAngularJSがテストします

it('should be transformed to <img>', function(){ 
    var elm = $compile('<custom-directive></custom-directive>')(scope); 
    scope.$digest(); 

    var t = elm.find('img'); // wrong! it replaces the element. it won't find another one inside 
//expect(elm).toBeAnImgElement ? 
}); 

正しいマッチャーが見つかりません。 私が見た中で最も近いのは内容(elm.html()またはelm.text())のチェックですが、私のタグは空です。

答えて

18

のようなdivの中にあなたのディレクティブをラップ:なぜ我々は `$ rootScopeが必要なのです

describe('Directive: custom', function() { 
    beforeEach(module('App')); 

    var element, $scope; 

    it('should be transformed to <img>', inject(function ($rootScope, $compile) { 
    $scope = $rootScope.$new(); 
    element = angular.element('<div><custom-directive></custom-directive></div>'); 
    element = $compile(element)($scope); 

    expect(element.children('img').length).toBe(1); 
    })); 
}); 
+0

$ダイジェスト();'ここに。?確かに、それはそれなしで動作しませんが、私はなぜ取得しません。 – thorn

+0

@thorn:それは必須ではありません。 – codef0rmer

+0

いいえ、そうです。私が書いたように、それなしでは動作しません。 – thorn

3

実際のHTMLElementオブジェクトを取得し、そのタグ名を確認することができます。 elm[0]と実際のHTMLElementでゲット:

expect(elm[0].tagName).toEqual('A');