Can I wait for multiple elements at the same time using WaitForElement?

For example I expect element1 OR element2 to appear.

I don't know which element will appear first. I expect one OR the other to appear, and then do some action depending on which element has appeared first.

Is it possible to do?

Answers

  • PeterSimonsPeterSimons GBMember ✭✭
    edited November 6

    There are a couple of ways i can think of that you could achieve this, I would recommend option 1 as it'll be more robust however it will make your test run for longer:

    1. You could wrap your app.WaitForElement in a try catch like this:

          try
          {
          app.WaitForElement("elementOne"); 
          //It will fail here and the exception will be swallowed if the element isn't found
          app.Tap("elementOne")
          }
          catch (Exception ex)
          {
              System.Diagnostics.Debug.WriteLine(ex);
          }
      // This try catch will get executed no matter what but will fail at the waitfor line if the first try already succeeded   
          try
          {
              app.WaitForElement("elementTwo"); 
              //If the first try catch works this'll fail, the error will be swallowed and the following tap won't get executed
              app.Tap("elementTwo")
          }
          catch (Exception ex)
          {
              System.Diagnostics.Debug.WriteLine(ex);
          }
      
    2. you could use app.query in an if statement doing it this way will execute instantly though

      if (app.Query(elementOne).Any())`
          {
              app.Tap(elementOne);
          }
          else
          {
              app.Tap(elementTwo);
          }
      

    I would also recommend creating a method for doing this so you can reuse the pattern in future something like this

        public static void TapEither(this IApp app, Func<AppQuery, AppQuery> elementOne, Func<AppQuery, AppQuery> elementTwo)
                {
                    try
                    {
                        app.WaitForElement(elementOne); 
                        app.Tap(elementOne);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
    
                    try
                    {
                        app.WaitForElement(elementTwo);
                        app.Tap(elementTwo);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
    

    Then this can be called in your test with the following step
    app.TapEither(a => a.Marked("elementOne"), b => b.Marked("elementTwo"));

Sign In or Register to comment.