2017-03-31 30 views
2

有像我如何使ViewChild工作在單元測試

@Component(
    selector: 'my-test', 
    template: 'none', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
) 
class MyTestComponent { 
    final AngularClientCache clientCache; 
    MyTestComponent(this.clientCache) { 
    assert(clientCache != null); 
    } 
} 

@Component(
    selector: 'test', 
    directives: const <dynamic>[MyTestComponent], 
    template: r'<my-test></my-test>', 
) 
class ComplexTestComponent { 
    @ViewChild(MyTestComponent) MyTestComponent testComponent; 
} 

@AngularEntrypoint() 
void main() { 
    tearDown(() => disposeAnyRunningTest()); 

    group('AngularClientCache',() { 
    test('should store and return value',() async { 

     final testBed = 
      new NgTestBed<ComplexTestComponent>().addProviders(<dynamic>[ 
     provide(AngularClientCache, useValue: new AngularClientCache()) 
     ]); 
     final fixture = await testBed.create(); 

     // Create an instance of the in-browser page loader that uses our fixture. 
     final loader = new HtmlPageLoader(
     fixture.rootElement.parent, 
     executeSyncedFn: (c) async { 
      await c(); 
      return fixture.update; 
     }, 
     useShadowDom: false, 
    ); 

     final complex = 
      await loader.getInstance<ComplexTestComponent>(ComplexTestComponent); 
     print(complex.testComponent); // <<<=== print `null` 
    }); 
    }); 
} 

測試?我怎樣才能到MyTestComponent組件的引用。我期望@ViewChild()這樣做,但它不。任何其他方法也是受歡迎的。

+0

據我所知,這應該工作。 – rkj

回答

2

馬坦Lurey在( https://github.com/dart-lang/angular_test/issues/50#issuecomment-291044761 碎)

resolvePageObject僅用於得到一個package:pageloader對象說明。

你想要做什麼,我想:

await fixture.update((c) { 
    expect(c.testComponent, isNotNull); 
}); 
+0

您的答案中的鏈接不起作用。我處於類似的情況,我需要@viewChild參考/對象在進行單元測試時通過。所以問了另一個問題https://stackoverflow.com/questions/46003458/how-to-get-viewchiled-reference-object-in-unit-test-spec-in-angular –

+0

感謝您的報告。鏈接是一個公關,合併時似乎消失了。這個q + a是關於Dart的,在TS測試中完全不同。 –