【问题标题】:How to check state of a switch toggle in Selenium using c#如何使用 c# 在 Selenium 中检查开关切换的状态
【发布时间】:2020-03-09 08:36:32
【问题描述】:

我正在尝试使用 selenium 验证开关是“打开”还是“关闭”,但我似乎无法正确处理。切换在加载网页时设置为打开位置,但在关闭时过滤结果在表格中等。它工作正常我只是检查获取我的硒测试以获取其当前状态。

  1. 元素。选定;总是返回 false(关于切换位置)
  2. 元素。启用;总是返回 true(关于切换位置)
  3. 字符串测试 = myToggle.GetAttribute("class");返回没有帮助的文本“slider round”
  4. string test1 = myToggle.GetAttribute("checked");为空
  5. 字符串 test2 = myToggle.GetAttribute("value");为空

代码如下:

<label class="switch">
<input type="checkbox" id="myToggle" checked />
<span class="slider round"></span>
</label>

检查切换位置并加载表格数据的代码:

   if (Amt == currentAmt ) {
    if ($("#myToggle").prop("checked") == true) {
        loadMyProducts('NAN', $("#total").val());
    }

我现在的测试是这样的

    [FindsBy(How = How.XPath, Using = "//*[@id='divTestAcc']/div[1]/p[9]/label/span")]
  public IWebElement myToggle { get; set; }

    public Boolean CheckMyToogleIsOnorOFF()
    {
        string test = myToggle.GetAttribute("class");
        Console.Write("checking "+ test);

        // string test1 = myToggle.GetAttribute("checked");
        //string test2 = myToggle.GetProperty("checked");
        // .Selected always returns false
        // .Enables always returns true 

        Boolean result;
        result = myToggle.Enabled;
        bool result1 = myToggle.Selected;

        if (result == true)
        {
            Console.WriteLine("My toggle is enabled");
        }
        else
        {
            Console.WriteLine("My toggle is not enabled");
        }
        return result;
    }

【问题讨论】:

  • 如果你的字符串 test = myToggle.GetAttribute("class");返回文本“slider round”然后您尝试验证 span 元素而不是 checkbox 元素。首先选择正确的元素,然后 .selected 属性必须正常工作

标签: javascript c# selenium selenium-chromedriver specflow


【解决方案1】:
// is it checked? 
var isChecked = driver.FindElement(By.XPath("//input[@type='checkbox']").Selected;

使用.Selected 属性应该可以实现您想要做的事情。我添加 driver.FindElement 语句的原因是为了确保您找到正确的元素 - 根据您的问题描述,我不确定您找到并测试的元素是否正确。

正如另一位用户指出的那样,如果GetAttribute("class") 返回slider round,那么您在这里查看的是错误的元素。确保首先找到 input 元素。

您的文件头 //*[@id='divTestAcc']/div[1]/p[9]/label/span 处的 XPath 将定位 span 元素,而不是 input -- input 是带有 checked 的那个,所以这就是我们需要测试的对象。

【讨论】:

  • 谢谢!这已经奏效了,我已经坚持了好几天了,但这解决了问题并在检查时返回 true,在未检查时返回 false!是的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2011-03-19
  • 1970-01-01
  • 2018-10-11
  • 2013-02-27
相关资源
最近更新 更多