testWidgets function

  1. @isTest
void testWidgets (String description, WidgetTesterCallback callback, { bool skip: false, Timeout timeout, bool semanticsEnabled: false })

Runs the callback inside the Flutter test environment.

Use this function for testing custom StatelessWidgets and StatefulWidgets.

The callback can be asynchronous (using async/await or using explicit Futures). Tests using the AutomatedTestWidgetsFlutterBinding have a default time out of two seconds, which is automatically increased for some expensive operations, and can also be manually increased by calling AutomatedTestWidgetsFlutterBinding.addTime. The maximum that this timeout can reach (automatically or manually increased) is defined by the timeout property, which defaults to TestWidgetsFlutterBinding.defaultTestTimeout.

If the enableSemantics parameter is set to true, WidgetTester.ensureSemantics will have been called before the tester is passed to the callback, and that handle will automatically be disposed after the callback is finished.

This function uses the test function in the test package to register the given callback as a test. The callback, when run, will be given a new instance of WidgetTester. The find object provides convenient widget Finders for use with the WidgetTester.

See also:

Sample code

testWidgets('MyWidget', (WidgetTester tester) async {
  await tester.pumpWidget(new MyWidget());
  await tester.tap(find.text('Save'));
  expect(find.text('Success'), findsOneWidget);
});

Implementation

@isTest
void testWidgets(
  String description,
  WidgetTesterCallback callback, {
  bool skip = false,
  test_package.Timeout timeout,
  bool semanticsEnabled = false,
}) {
  final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
  final WidgetTester tester = WidgetTester._(binding);
  timeout ??= binding.defaultTestTimeout;
  test(
    description,
    () {
      SemanticsHandle semanticsHandle;
      if (semanticsEnabled == true) {
        semanticsHandle = tester.ensureSemantics();
      }
      tester._recordNumberOfSemanticsHandles();
      test_package.addTearDown(binding.postTest);
      return binding.runTest(
        () async {
          await callback(tester);
          semanticsHandle?.dispose();
        },
        tester._endOfTestVerifications,
        description: description ?? '',
      );
    },
    skip: skip,
    timeout: timeout,
  );
}