Leonardo Godde
Leonardo Godde

Reputation: 21

(WidgetTest) Test Button State (enabled or disabled)

In the initial state, when accessing a view, the button must be disabled and after a specific action, the button must be enabled. Any ideas on how to test this behavior?

Upvotes: 2

Views: 1531

Answers (1)

omar hatem
omar hatem

Reputation: 1979

You can do it by using tester.widget<ElevatedButton>(buttonFinder).enabled

And here is a full example of a test I did before on the same scenario:

testWidgets('Button disabled when loading and enabled after result',
          (WidgetTester tester) async {
        LocationBlocMock locationBlocMock = LocationBlocMock();
    
        await tester.pumpWidget(
          MaterialApp(
            home: Builder(
              builder: (context) {
                return BlocProvider<LocationBloc>(
                  create: (BuildContext context) => locationBlocMock,
                  child: LocationAccess(),
                );
              },
            ),
          ),
        );
    
        locationBlocMock.add(GetCurrentLocation());
    
        await tester.pump(const Duration(seconds: 1));
    
        final buttonFinder = find.byKey(const Key("give_permission_key"));
    
        expect(buttonFinder, findsOneWidget);
        expect(tester.widget<ElevatedButton>(buttonFinder).enabled, isFalse);
    
        await tester.pump(const Duration(seconds: 1));
    
        expect(tester.widget<ElevatedButton>(buttonFinder).enabled, isTrue);
    
        locationBlocMock.close();
      });

Upvotes: 5

Related Questions