0
0
FlutterHow-ToBeginner · 4 min read

How to Use Widget Test in Flutter: Simple Guide

To use widget test in Flutter, write tests inside the testWidgets function where you build your widget with WidgetTester. Use methods like pumpWidget to load the widget and expect to verify UI elements or behavior.
📐

Syntax

The basic syntax for a Flutter widget test uses the testWidgets function. Inside it, you get a WidgetTester object to build and interact with widgets.

  • testWidgets('description', (WidgetTester tester) async { ... }): Defines a widget test.
  • tester.pumpWidget(widget): Builds the widget in a test environment.
  • expect(find.byType(Type), findsOneWidget): Checks if a widget of a certain type is found.
dart
testWidgets('MyWidget has a title and message', (WidgetTester tester) async {
  await tester.pumpWidget(MyWidget());
  expect(find.text('Hello'), findsOneWidget);
  expect(find.byType(Text), findsOneWidget);
});
💻

Example

This example shows a simple widget test for a widget that displays a text. It builds the widget, then checks if the text is present.

dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('Text widget displays Hello', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: Text('Hello'),
      ),
    ));

    expect(find.text('Hello'), findsOneWidget);
  });
}
Output
Test passes if the text 'Hello' is found exactly once in the widget tree.
⚠️

Common Pitfalls

Common mistakes when writing widget tests include:

  • Not wrapping widgets with MaterialApp or Scaffold when needed, causing missing theme or context errors.
  • Forgetting to use await tester.pumpWidget() before assertions.
  • Using find.text or find.byType incorrectly, leading to failed tests.
dart
/* Wrong: Missing MaterialApp wrapper */
await tester.pumpWidget(Text('Hello'));
expect(find.text('Hello'), findsOneWidget);

/* Right: Wrap with MaterialApp */
await tester.pumpWidget(MaterialApp(home: Text('Hello')));
expect(find.text('Hello'), findsOneWidget);
📊

Quick Reference

MethodPurpose
testWidgets(description, callback)Defines a widget test case
tester.pumpWidget(widget)Builds the widget in the test environment
tester.tap(finder)Simulates a tap gesture on a widget
tester.pump()Rebuilds the widget tree after state changes
find.text('text')Finds widgets displaying specific text
find.byType(Type)Finds widgets of a specific type
expect(finder, matcher)Asserts conditions about widgets found

Key Takeaways

Use testWidgets with WidgetTester to build and test widgets in Flutter.
Always wrap widgets with MaterialApp or Scaffold if they depend on context or theme.
Use find and expect to locate widgets and verify UI behavior.
Remember to await pumpWidget before making assertions.
Simulate user actions with tester methods like tap and pump.