2

I am trying to submit a login form with Selenium from C#. But I can't make it wait after submit to wait the new page to load. Only thing that has worked is Thread.Sleep. What should I do to make it wait?

[TestFixture]
public class SeleniumTests
{
    private IWebDriver _driver;

    [SetUp]
    public void SetUpWebDriver()
    {
        _driver = new FirefoxDriver();

        // These doesn't work
        //_driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(10));
        //_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
    }

    [Test]
    public void SubmitTest()
    {
        _driver.Url = "http://mypage.com";

        _driver.FindElement(By.Name("username")).SendKeys("myname");
        _driver.FindElement(By.Name("password")).SendKeys("myeasypassword");
        _driver.FindElement(By.TagName("form")).Submit();

        // It should wait here until new page is loaded but it doesn't

        // So far this is only way it has waited and then test passes
        //Thread.Sleep(5000);

        var body = _driver.FindElement(By.TagName("body"));
        StringAssert.StartsWith("Text in new page", body.Text);
    }
}
Lassi Autio
  • 1,147
  • 1
  • 13
  • 35

2 Answers2

2

I've found the best way to do this is to wait for an element on the first page to go stale, then wait for the element on the new page. The problem you are likely having is that you are waiting for the body element... which is going to exist on every page there is. If you want to just wait for an element, you should find an element that is unique to the page you are navigating to. If you still want to use the body tag, you can do this...

public void SubmitTest()
{
    _driver.Url = "http://mypage.com";

    _driver.FindElement(By.Name("username")).SendKeys("myname");
    _driver.FindElement(By.Name("password")).SendKeys("myeasypassword");
    IWebElement body = _driver.FindElement(By.TagName("body"));
    _driver.FindElement(By.TagName("form")).Submit();

    body = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.TagName("body")))
    StringAssert.StartsWith("Text in new page", body.Text);
}
JeffC
  • 22,180
  • 5
  • 32
  • 55
0

Answer was practically in JeffC's answer:

I've found the best way to do this is to wait for an element on the first page to go stale, then wait for the element on the new page.

I solved this with this answer: https://stackoverflow.com/a/15142611/5819671

I put following code before reading body element from new page and now it works:

new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists((By.Id("idThatExistsInNewPage"))));
Community
  • 1
  • 1
Lassi Autio
  • 1,147
  • 1
  • 13
  • 35