尝试通过Selenium清除文本时出现InvalidElementStateException

时间:2018-05-25 11:40:05

标签: c# selenium selenium-webdriver xpath webdriverwait

我正在测试的Web应用程序在删除记录时需要确认。

我已创建测试以输入删除此记录的正确理由。

执行此操作的代码如下:

DeleteFieldButton.
            Click();
        WaitMethods.WaitForElementToBeDisplayed(RemovalReason, 20);
        RemovalReason
            .Click();
        RemovalReason
            .Clear();
        RemovalReason
            .SendKeys("Automated Test - Delete Field");

文本框的XPath如下:

private Label RemovalReason = new Label(By.XPath("//*[@placeholder = 'Removal reason']"));

每当运行测试时,都会返回以下异常。

OpenQA.Selenium.InvalidElementStateException
HResult=0x80131500
Message=Cannot clear By.XPath: //*[@placeholder = 'Removal reason'] as it is 
not declared as a writable text element
Source=web
StackTrace:
at web.Elements.Common.Element.Clear()
at Daera.Efs.Test.E2e.PageObjects.ApplicationSummary.DeleteField(String 
FieldIDToDelete) in 
C:\Code\Local\WebApp.E2e\PageObjects\ApplicationSummary.cs:line 280
 at Test.E2e.Tests.ApplicationSummaryTest.Delete_Wider_General_Field_From_Application_Summary() in C:\Code\Local\WebApp.E2e\Tests\ApplicationSummaryTest.cs:line 45

以下是Web应用程序中元素的HTML:

<input ng-keypress="dialog.keypress($event)" md-autofocus="" ng-model="dialog.result" placeholder="Removal reason" class="ng-valid md-input ng-not-empty md-autofocus ng-touched ng-dirty ng-valid-parse" aria-label="Removal reason" id="input_22" aria-invalid="false" style="">

2 个答案:

答案 0 :(得分:1)

根据HTML,您已将<input>元素与placeholder 属性共享为删除原因 Angular 元素,因为你必须发送文本,你必须诱导 WebDriverWait 使元素可点击,如下所示:

IWebElement myElem = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//input[@class='ng-valid md-input ng-not-empty md-autofocus ng-touched ng-dirty ng-valid-parse' and starts-with(@id,'input_') and @placeholder='Removal reason']")));
myElem.Click();
myElem.Clear();
myElem.SendKeys("Automated Test - Delete Field");

答案 1 :(得分:0)

我遇到了同样的问题,只是我试图在不允许使用破折号的日期字段中输入破折号。我通过手动输入带破折号的日期来解决这个问题,但该日期并未填充。 (该字段也不接受字母-仅接受数字)。现在,我的测试输入的日期没有破折号,并且成功通过了!