How to make ViewChild work in a unit test


I have a test like

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

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

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(
        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.


Matan Lurey explained in ( 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 *