I am trying write to some tests for a simple credit card form widget.
Each test passes when run individually but the second one fails and throws the following exception when I run both of them.
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following IndexError was thrown running a test:
RangeError (index): Index out of range: no indices are valid: 0
I tried different approaches such as resetting testedWidget to null in tearDown hook but nothing worked as intended.
Here is the test file I wrote:
void main() {
final validCardNumber = '1234123412341234';
final validExpirationDate = '11/25';
final invalidExpirationDate = '32/25';
final validCvv = '123';
Widget testedWidget;
setUp(() {
testedWidget = testableAddCardScreen(AddCardFormScreen());
});
testWidgets('Form is submittable if inputs are valid', (
WidgetTester tester,
) async {
await tester.pumpWidget(testedWidget);
await tester.pumpAndSettle();
final inputs = find.byType(TextInput);
await tester.enterText(inputs.at(0), validCardNumber);
await tester.enterText(inputs.at(1), validExpirationDate);
await tester.enterText(inputs.at(2), validCvv);
await tester.pumpAndSettle();
final button = evaluateWidget<Button>(find.byType(Button));
expect(button.isDisabled, false);
});
testWidgets('Form is not submittable if inputs are invalid', (
WidgetTester tester,
) async {
await tester.pumpWidget(testedWidget);
await tester.pumpAndSettle();
final inputs = find.byType(TextInput);
await tester.enterText(inputs.at(0), validCardNumber);
await tester.enterText(inputs.at(1), invalidExpirationDate);
await tester.enterText(inputs.at(2), validCvv);
await tester.pumpAndSettle();
final button = evaluateWidget<Button>(find.byType(Button));
expect(button.isDisabled, true);
});
}
I also use some utils functions to make widgets testable.
Widget testableAddCardScreen(Widget child) {
return testableLocalizedWidgetFactory(
ChangeNotifierProvider(
create: (_) => AddCardProvider(
apiClientService: MockApiClientService(),
successCallback: () {},
failureCallback: () {},
),
child: child,
),
);
}