flutterwidget-test-flutter

Flutter widget test on custom checkbox


I have a custom checkbox like this:

   FeedbackCheckBox(
      title: 'Test',
      onChanged: (value) {
        setState(
          () {
            isNeedComeBack = value;
          },
        );
      },
    )

and these are implementations:

class FeedbackCheckBox extends HookWidget {
  const FeedbackCheckBox({
    Key? key,
    required this.title,
    required this.onChanged,
    this.textStyle,
    this.padding,
  }) : super(key: key);

  final String title;
  final TextStyle? textStyle;
  final ValueChanged<bool> onChanged;
  final EdgeInsets? padding;
  @override
  Widget build(BuildContext context) {
    final isNeedComeBack = useState<bool>(false);

    return Padding(
      padding: padding ?? const EdgeInsets.only(top: 12),
      child: CustomCheckbox(
        value: isNeedComeBack.value,
        label: title,
        onTap: () {
          isNeedComeBack.value = !isNeedComeBack.value;
          onChanged(isNeedComeBack.value);
        },
      ),
    );
  }
}

Now I want to write a widget test for it. I want to when onTap on CustomCheckbox tapped, onChanged: (value) recieved the right value.

This is my test:

testWidgets("FeedbackCheckBox widget onChanged works",
    (WidgetTester tester) async {
  bool clicked = false;
  _onTap(v) => clicked = v;

  var mockWidget = FeedbackCheckBox(title: "hhh", onChanged: _onTap);
  final mockCustomCheckboxWidget =
      CustomCheckbox(value: false, onTap: () {});
  await tester.pumpWidget(withMaterialApp(child: mockWidget));
  var customCheckBox =
      tester.firstWidget(find.byWidget(mockCustomCheckboxWidget));
  // await tester.tap(inkWellFinder);
  // await tester.pumpAndSettle();
  // expect(clicked, true);
});

I found customCheckBox but how can I trigger onTap and receive a value on FeedbackCheckBox onChanged?


Solution

  • I fixed this problem, This is new test:

        testWidgets("FeedbackCheckBox widget onChanged works",
            (WidgetTester tester) async {
          bool clicked = true;
          _onTap(v) {
            return clicked = v;
          }
    
          var mockWidget = FeedbackCheckBox(title: "hhh", onChanged: _onTap);
          await tester.pumpWidget(withMaterialApp(child: mockWidget));
          await tester.tap(find.byType(CustomCheckbox));
          await tester.tap(find.byType(CustomCheckbox));
          expect(clicked, false);
        });
      });
    }