How can I run a flutter widget test for cupertino data picker?

Viewed 383

I am trying to write test for cupertino date picker but I couln't found to see any result for that. How can I choose a spesific a datetime for widget test.

testWidgets("description", (WidgetTester tester)async{
    await tester.pumpWidget(MaterialApp(home: MyPage()));

    final textField=find.byKey(Key("nameTextField"));
    final datePicker=find.byKey(Key("birthDatePicker"));
    final button=find.byType(ElevatedButton);


    await tester.enterText(textField, "not important");
    await tester.drag(datePicker, Offset(0.0, 10.0)); ///Here the problem ?

    await tester.press(button);

    await tester.pump();
    expect(find.text("Error Text"), findsOneWidget);
  });

My question is, how can I choose the 1/1/2021 for widget test ?

1 Answers

Take a look at the tests that are implemented for the widget, these turn out to be self-explanatory. They tend to use references throughout the texts and make movements with a constant offset.

https://github.com/flutter/flutter/blob/master/packages/flutter/test/cupertino/date_picker_test.dart

I also leave you an example here below

testWidgets('picker automatically scrolls away from invalid date on day change', (WidgetTester tester) async {
      late DateTime date;
      await tester.pumpWidget(
        CupertinoApp(
          home: Center(
            child: SizedBox(
              height: 400.0,
              width: 400.0,
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date,
                onDateTimeChanged: (DateTime newDate) {
                  date = newDate;
                },
                initialDateTime: DateTime(2018, 2, 27), // 2018 has 28 days in Feb.
              ),
            ),
          ),
        ),
      );

      await tester.drag(find.text('27'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file
      await tester.pump();
      expect(
        date,
        DateTime(2018, 2, 28),
      );

      await tester.drag(find.text('28'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file
      await tester.pump(); // Once to trigger the post frame animate call.

      // Callback doesn't transiently go into invalid dates.
      expect(
        date,
        DateTime(2018, 2, 28),
      );
      // Momentarily, the invalid 29th of Feb is dragged into the middle.
      expect(
        tester.getTopLeft(find.text('2018')).dy,
        tester.getTopLeft(find.text('29')).dy,
      );

      await tester.pump(); // Once to start the DrivenScrollActivity.
      await tester.pump(const Duration(milliseconds: 500));

      expect(
        date,
        DateTime(2018, 2, 28),
      );
      expect(
        tester.getTopLeft(find.text('2018')).dy,
        tester.getTopLeft(find.text('28')).dy,
      );
    });
Related