How to make ViewChild work in a unit test

Issue

I have a test like

@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`
    });
  });
}

How can I get a reference to the MyTestComponent component.
I expected @ViewChild() to do it, but it doesn’t. Any other approach is welcome as well.

Solution

Matan Lurey explained in (https://github.com/dart-lang/angular_test/issues/50#issuecomment-291044761 broken)

resolvePageObject is only for getting a package:pageloader object.

What you’re trying to do, I think:

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

Answered By – Günter Zöchbauer

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *