2016-10-27 3 views
1
我々は我々が行うAngular2でサービスのハンドルを取得したい

...ユニットテストの属性ディレクティブのハンドルを取得する方法は?最終リリース

がどのようにハンドルを取得することができますなど

let fix = TestBed.createComponent(TestComponent); 
let injector = fix.debugElement.injector; 
let service = injector.get(MyService); 

、今我々が注入されたサービスをスパイすることができ、私がそれについてスパイすることができるように、テストコンポーネントによって使用される属性ディレクティブに?

答えて

1

あなたは子供のインジェクタ

let directive = fixture.debugElement.children[0].injector.get(MyDirective); 
+0

ありがとうございました。 children [0]が指示要素であると仮定していますが、この答えを受け入れることになります。この前提を成立させない私自身の答えを提供しました。再度、感謝します。 – danday74

1

のみ問題のディレクティブに縛ら要素をターゲットにし@peeskillet答えに若干の微調整からそれを取得する必要があります。

let fix = TestBed.createComponent(TestComponent); 
    // this will return multiple elements if the test component uses the directive multiple times 
    let directiveEls = fix.debugElement.queryAll(By.directive(MyDirective)); 
    let directive = directiveEls[0].injector.get(MyDirective) as MyDirective; 
+0

もっと良い答え。 –

+0

あなたは私に正しい道を導いてくれてありがとう:) – danday74

関連する問題