mardi 3 novembre 2020

Test class which makes API call within

I have a class which is using ViewModelBuilder (package stacked) to provide information to its children. When I am creating the provider I am calling the onModelReady method to populate the fields I need from my model. Within the model, upon calling loadData() an API call will be made.

How do I test my widget? I think what I am doing currently is bad practice because I am instantiating the widget in the test, which will call the build method, which makes the API call. At the moment I don't have the backend ready so there is no API call, the loadData() just populates it with a mock, which happens to be the same thing I use in my test in the expect.

Here is the code for the widget:

class ActiveExams extends MenuOptionsView {
  ActiveExams() : super(ACTIVE_EXAMS_TEXT, Icon(Icons.local_library));

  @override
  Widget build(BuildContext context) {
    final numberOfColumns = 2;
    return ViewModelBuilder<ActiveExamsModel>.reactive(
      viewModelBuilder: () => ActiveExamsModel(),
      onModelReady: (model) => model.loadData(),
      builder: (context, model, _) => Scaffold(
          body: GridView.count(
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
        padding: EdgeInsets.all(10),
        crossAxisCount: numberOfColumns,
        children:
            // Map the information (subject, name, image) of each active exam to a grid tile.
            model.activeExams.map<Widget>((exam) {
          return Provider.value(value: exam, child: ExamGridItem());
        }).toList(),
      )),
    );
  }
}

and the test:

final activeExams = ActiveExams();
  testWidgets('Displays exams', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(home: activeExams));

    var examFinder = find.byType(ExamGridItem, skipOffstage: false);
    expect(examFinder, findsNWidgets(examMocks.length));
  });

Aucun commentaire:

Enregistrer un commentaire