Flutter: Mapbox onMapCreated not called in widget test

763 views Asked by At

I'm using the Mapbox map and when I run the app in an emulator, it works fine. However, in my widget test, the onMapCreated method is never called, which makes it impossible to test the behavior of the app.

My MapWidget (condensed):

class MapWidget extends StatefulWidget {
  final LatLng initialCameraPositionCoordinates;
  final double initialZoomLevel;

  const MapWidget({
    Key key,
    @required this.initialCameraPositionCoordinates,
    @required this.initialZoomLevel,
   }) : super(key: key);
  
  @override
  State createState() => MapWidgetState();
}

class MapWidgetState extends State<MapWidget> {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<Cubit, State>(
      builder: (context, state) {
        return MouseRegion(
          cursor: MouseCursor.defer,
          child: MapboxMap(
            onMapCreated: _onMapCreated,
          ),
        );
      },
    );
}

void _onMapCreated(MapboxMapController controller) async {
    print("This is never called in the test");
}

And the corresponding widget test looks like this:

void main() {
    testWidgets("Mapbox", (WidgetTester tester) async {
        await tester.pumpWidget(
          BlocProvider(
            create: (_) => _cubit,
            child: MaterialApp(
              home: MapWidget(
                initialCameraPositionCoordinates:
                    _initialCameraPositionCorrdinates,
                initialZoomLevel: _initialZoomLevel,
              ),
            ),
          ),
        );
        await tester.pump(Duration(seconds: 10));
      });
}

No exception is thrown, meaning it renders fine. However, the print statement in the onMapCreated is never printed.

Running the app in an emulator, the print statement is called.

Does anyone have an idea what's going on here?

1

There are 1 answers

0
cohenadair On

I ran into the same issue, and worked around it by manually invoking the callbacks. Something like this in your widget test:

var mapboxMap = tester.firstWidget(find.byType(MapboxMap)) as MapboxMap;
mapboxMap.onMapCreated!(<mocked controller>);
mapboxMap.onStyleLoadedCallback!();

Where "<mocked controller" is an instance of your MapboxMapController mock.

I imagine the underlying issue has to do with the native map view not actually being loaded during widget tests, and therefore, no callbacks are invoked.