首页 > 解决方案 > 等待元素,但元素始终存在 (POM)

问题描述

我被困在一个关于等待元素在单击之前可见的问题上。问题是我正在测试所有元素的系统总是可见的。导致系统永远不会改变页面只是打开弹出窗口:s。因此,如果我创建一个等待元素方法,即使它位于当时打开的窗口的背景中,它也会始终找到该元素。

有没有人遇到这个问题并有一个好的解决方案或代码示例,我将不胜感激。

编辑:如果我打开了一个弹出窗口,我想返回登录页面并调用 ClickOnArticleNumber 方法。它会在有时间关闭弹出页面之前找到xpath,并且测试可能会失败,因为它甚至在正确页面上之前就调用了Click。

我希望这能解决我的问题。

    public void ClickOnArticleNumber()
    {
        waitForElement(By.XPath("xpath"), 20);
        AddArticleNumber.Click();
    }

亲切的问候

罗宾

标签: c#selenium-webdriver

解决方案


重申我认为我理解的问题......

您有一个具有始终打开的主页的站点。许多动作都是在弹出窗口中完成的……弹出一个弹出窗口,你做一些动作,弹出窗口就会关闭。

当您在弹出窗口关闭时尝试在主页上执行操作时,就会出现问题。主页上的元素始终存在,因此 Selenium 看到它并尝试执行该操作,但该操作被弹出窗口阻止。

假设我上面所说的是真的,在处理弹出窗口时你会想要非常清晰。启动弹出窗口时,您将希望等待弹出窗口可见,然后执行您的操作。当弹出窗口关闭时,您将需要等待一些与弹出窗口相关的元素不可见,表明弹出窗口不再可见,然后再尝试在基本页面上执行操作。

为此,您需要为触发弹出窗口关闭的每个操作添加等待。我使用页面对象模型,所以我会做这样的事情......

弹出窗口的一些示例 HTML

<div id="actionDialog" ...>
    ...
    <button id="save">Save</button>
    <button id="cancel">Cancel</button>
</div>

In this HTML we have a popup, the Action Dialog, that has two buttons, the Save and Cancel buttons. Clicking either of these buttons causes the Action Dialog to close so we will want to add a wait after each. Since you are likely to have several buttons that will cause the dialog to close, you create a method that does nothing but waits for the dialog to close so it can be easily called from the other methods and stores the "wait for close" logic in one place.

In the page object for the ActionDialog, I would have a few methods: one to wait for the dialog to close and a couple others to click the save or cancel buttons.

private By actionDialogLocator = By.Id("actionDialog");
private By cancelButtonLocator = By.Id("cancel");
private By saveButtonLocator = By.Id("save");

public void Cancel()
{
    Driver.FindElement(cancelButtonLocator).Click();
    WaitForDialogToClose();
}
public void Save()
{
    Driver.FindElement(saveButtonLocator).Click();
    WaitForDialogToClose();
}
private void WaitForDialogToClose()
{
    new WebDriverWait(Driver, TimeSpan.FromSeconds(5)).Until(ExpectedConditions.InvisibilityOfElementLocated(actionDialogLocator));
}

Now when you call Click() or Save(), the script will wait for the dialog to close, preventing the next call to some element on the main page from failing because the dialog will be closed before that action is attempted.


推荐阅读