Bram  Vanbilsen
Bram Vanbilsen

Reputation: 6505

Flutter async callback testing

I'm trying to test out a button in Flutter using the test Flutter lib. I use the following code for the test:

await tester.tap(find.widgetWithText(GestureDetector, "ref size"));
expect(testContainerState.childWidth, 200.0);

When tapping on the button, the following function gets invoked:

  void setToRefSize() async {
    print("SETTING REF SIZE (0)");
    ui.Image img = await widget.referenceImages[referenceImageIndex].getImageData();
    print("SETTING REF SIZE (1)");
  }

But for some reason, only the first print statement produces output. I'm pretty sure that it has to do with this being async

ui.Image img = await widget.referenceImages[referenceImageIndex].getImageData();

The getImageData() method is defined as follows:

  Future<ui.Image> getImageData() async {
    Completer<ui.Image> completer = new Completer<ui.Image>();
    image
      .resolve(new ImageConfiguration())
      .addListener((ImageInfo info, bool _) => completer.complete(info.image));
    return completer.future;
  }

The strange thing is that all of this works when testing the button manually, so just running it on a device and tapping the button myself.

EDIT Taking a look at it again, the problem might be that the listener on the image in the getImageData() method is not done in sync. Still not certain on how to fix it though.

Upvotes: 1

Views: 2580

Answers (1)

pasotee
pasotee

Reputation: 348

According to the research I've done on this subject, flutter tests supports waiting for async methods calls but doesn't support awaiting async callbacks.

When you tap the button, the action is done immediately, the button then triggers his callback and causes the async suspension, because the tester is already on the next line, but the callback is not yet finished.

Upvotes: 1

Related Questions