Using Flutter, I’d like to write a test to check for existence of a given element. How do I do that?
Also, will the test throw errors when it cannot find any matching elements?
Yes, you can use the find utility (or more generally the Finder class). Finders are quite powerful in what you can express with them, including checking for existence of widgets in the UI or even check how many of them are there. We have plenty of examples in the framework tests. Here are some examples:
// check that MyWidget is displayed expect(find.byType(MyWidget), findOneWidget); // check that 5 widgets of type MyWidgets are displayed expect(find.byType(MyWidget), findNWidgets(5));
The finder itself does not throw errors, but
expect does when the matcher (e.g.
findOneWidget) is not satisfied. If you need to interact with the widget rather than simply assert its existence, use one of the methods in WidgetTester, e.g.:
// Get the layout size of the render object for the given widget tester.renderObject<RenderBox>(find.byType(Text)).size;
Answered By – Yegor
Answer Checked By – Gilberto Lyons (FlutterFixes Admin)