Reputation: 91
I would like to check if an element exists or not. Something like a function that returns a Boolean. Or something similar to a function in Selenium 'ifExists' which wouldn't throw an exception if the element didn't necessarily exist and it would go about continuing the process without stopping in between when an element isn't found. There are similar things that exist on flutter_test but I have been unable to use it alongside flutter_driver so far.
Upvotes: 3
Views: 3381
Reputation: 11
try-catch approach didn't work for me.
I have written a peace of code to do the trick for me
Future<bool> isPresent(SerializableFinder finder, FlutterDriver driver, {Duration timeout = const Duration(seconds: 1)}) async {
Stopwatch s = new Stopwatch();
s.start();
await driver.waitFor(finder, timeout: timeout);
s.stop();
if(s.elapsedMilliseconds >= timeout.inMilliseconds){
return false;
}else{
return true;
}
}
Future<void> testStep() async {
final exists = await isPresent(find.byValueKey("accountMenu"), driver);
if (exists ) {
...
}
}
if the time it took for the "driver.waitFor" function to find our widget was more than the timeout, then the widget is not present.
Upvotes: 1
Reputation: 2163
According to Flutter issue #15852, there is currently no such possibility so far.
But one workaround mentioned in this issue by the user jonsamwell is to use the waitFor
method by flutter driver and wrap it in a try/catch to wait if it times out. If it times out, the element is not there, if it does not time out, the element is present:
Future<void> testStep() async {
final isOpen = await isPresent(find.byType("Drawer"), world.driver);
if (isOpen) {
...
}
}
Future<bool> isPresent(SerializableFinder finder, FlutterDriver driver, {Duration timeout = const Duration(seconds: 1)}) async {
try {
await driver.waitFor(finder, timeout: timeout);
return true;
} catch (e) {
return false;
}
}
Obviously, you have to calculate the waiting time according to your use-case to consider any loading times.
Upvotes: 5