Selenium无法检查切换状态是打开还是关闭(它总是显示)



我有一个可点击的开关来打开/关闭它。我正在使用Java Selenium检查状态(开/关(,然后单击它,然后再次检查状态。

根据此处和此处的讨论,我使用isSelected()检查状态,但它似乎无法正常工作。

这是一段 HTML 代码。

<div formly-field="" ng-repeat="field in fields " ng-show="!field.hide" class="formly-field ng-scope ng-isolate-scope txtToggle topToggle formly-field-toggleSwitch" options="field" model="field.model || model" original-model="model" fields="fields" form="theFormlyForm"
form-id="formly_35" form-state="options.formState" form-options="options" index="$index">
<div class="form-group ng-scope" ng-class="{'has-error': showError}">
<div class="col-xs-12 clearfix toggleRow">
<div class="toggleWrapper switch-on" data-ng-class="{'switch-off': !model[options.key], 'switch-on': model[options.key]}">
<div role="radio" class="toggle-switch ng-isolate-scope ng-valid" ng-class="{ 'disabled': disabled }" ng-model="model[options.key]" id="formly_2_toggleSwitch_AllowContactSMS_0" name="formly_2_toggleSwitch_AllowContactSMS_0" formly-custom-validation=""
ng-click="options.templateOptions['onClick'](model[options.key], options, this, $event)" aria-describedby="formly_2_toggleSwitch_AllowContactSMS_0_description">
<div class="toggle-switch-animate switch-on" ng-class="{'switch-off': !model, 'switch-on': model}"><span class="switch-left ng-binding" ng-bind="onLabel">On</span><span class="knob ng-binding" ng-bind="knobLabel"> </span><span class="switch-right ng-binding" ng-bind="offLabel">Off</span></div>
</div>
</div>
<div class="switchLabel group" ng-class="to.subLabel ? 'group' : 'single'">
<span class="switchTitle ng-binding">Toggle</span>
<!-- ngIf: to.subLabel --><span ng-if="to.subLabel" class="switchSubTitle ng-binding ng-scope">alerts</span>
<!-- end ngIf: to.subLabel -->
</div>
</div>
<!-- ngIf: to.description -->
</div>
</div>

这就是硒检查它的方式

WebElement toggle = driver.findElement(By.xpath("//*[@name='formly_35']/child::div[1]//*[contains(@class,'toggle-switch-animate')]"));
boolean onOff = toggle.isSelected();
if (onOff.isSelected()) {
log.debug("IS ON");
} else {
log.debug("IS OFF");
}
toggle.click();
if (onOff.isSelected()) {
log.debug("IS ON");
} else {
log.debug("IS OFF");
}

我可以在浏览器上看到单击了切换开关并将状态从打开更改为关闭或从关闭更改为打开,但是Selenium总是说IS OFF.

在这种情况下,可以使用isSelected来检查切换开关是否打开/关闭吗?如果没有,解决方法是什么?谢谢。

我会更改它以查看该类是否包含打开。

WebElement toggle = driver.findElement(By.xpath("//*[@name='formly_35']/child::div[1]//*[contains(@class,'toggle-switch-animate')]"));
boolean onOff = toggle.getAttribute("class").contains("switch-on");
if (onOff) {
log.debug("IS ON");
} else {
log.debug("IS OFF");
}

toggle.click();

if (onOff) {
log.debug("IS ON");
} else {
log.debug("IS OFF");
}

最新更新