Flutter - how to correctly unit test FutureBuilder

1k views Asked by At

I'm trying to unit test widgets inside a FutureBuilder but I can't figure it out.

I've got a widget that has a FutureBuilder with a builder that returns a CameraPreview widget when the connection state is done:

    body: FutureBuilder<void>(
      future: _initializeControllerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // If the Future is complete, display the preview.
          return CameraPreview(_controller);
        } else {
          // Otherwise, display a loading indicator.
          return const Center(child: CircularProgressIndicator());
        }
      },
    ),

Here's how I created the future:

  Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.
      widget.camera,
      // Define the resolution to use.
      ResolutionPreset.medium,
    );

    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

And here's my test:

testWidgets('Camera preview is available',
    (WidgetTester tester) async {
  await _buildCameraScreenPage(tester);
  await tester.pump();

  expect(find.byType(CameraPreview), findsOneWidget,
      reason: 'Camera preview should be visible.');
});

I've debugged it and snapshot.connectionState is never done (always waiting) so it skips the line which returns a CameraPreview. I've tried tester.pumpAndSettle() too but it times out.

Any ideas?

0

There are 0 answers