I'm following the https://codelabs.developers.google.com/codelabs/flutter-app-testing and was stuck on step 6.
In function in file test/favorites_test.dart , the test fails if I changed the i+=2 to i++ and I don't know why. If the total items is less than 6, it can pass too. Why the number is so important in test.
It is a simple app, when tap the close button, just delete from list
//test/favorites_test.dart
Widget createFavoritesScreen() => ChangeNotifierProvider<Favorites>(
create: (context) {
favoritesList = Favorites();
return favoritesList;
},
child: const MaterialApp(
home: FavoritesPage(),
),
);
void addItems() {
for (var i = 0; i < 10; i += 2) {
favoritesList.add(i);
}
}
void main() {
group('Favorites Page Widget Tests', () {
testWidgets('Test if ListView shows up', (tester) async {
await tester.pumpWidget(createFavoritesScreen());
addItems();
await tester.pumpAndSettle();
expect(find.byType(ListView), findsOneWidget);
});
testWidgets('Testing Remove Button', (tester) async {
await tester.pumpWidget(createFavoritesScreen());
addItems();
await tester.pumpAndSettle();
var totalItems = tester.widgetList(find.byIcon(Icons.close)).length;
await tester.tap(find.byIcon(Icons.close).first);
await tester.pumpAndSettle();
expect(tester.widgetList(find.byIcon(Icons.close)).length,
lessThan(totalItems));
expect(find.text('Removed from favorites.'), findsOneWidget);
});
});
}
Finally, I found the solution.
In
testWidgets
, the test runs in size (2400,1800) according totester.view.physicalSize
. (I don't know why the test page is not shown fully)After
tester.view.physicalSize = Size(10000, 10000)
, the test passed.Don't forget to call
tester.view.resetPhysicalSize()
or it will affect the following widget tests.