如何使ViewChild在单元测试中工作

时间:2017-03-31 16:23:21

标签: angular dart dart-unittest

我有一个像

这样的测试
@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()能够做到这一点,但事实并非如此。任何其他方法也是受欢迎的。

1 个答案:

答案 0 :(得分:2)

Matan Lurey解释说( https://github.com/dart-lang/angular_test/issues/50#issuecomment-291044761 破碎)

  

resolvePageObject仅用于获取package:pageloader个对象。

     

我想你要做的是:

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