问题
So I have this problem where I run a protractor/selenium test and sometimes a radio-button is already checked during the test and sometimes its not.
etc:
<div id="TRUCK" class="radio-item checked" data-gtm="truck">
or
<div id="TRUCK" class="radio-item" data-gtm="deliveryOpt-truck">
where you can see the class sometimes have the "checked" init and sometimes not.
What I am trying to do solve is that I want to make a function that clicks IF the radio-button is not checked and if its already checked then we just continue.
What I managed to do is:
it('Clicking Truck button', function (done) {
browser.driver
.then(() => browser.wait(EC.presenceOf(element(by.id("TRUCK")))), 30000, "Timed out button")
.then(() => browser.executeScript("arguments[0].click();",element(by.id("TRUCK")).getWebElement()))
.then(() => done());
however the problem is that it will uncheck it if the radio-button is already checked which is not good. So again.
I am trying to make a function that clicks. If the radio-button is not checked then we click. If its already checked then we continue.
How am I able to do that?
回答1:
Seems you were close. To identify an element when the class attribute doesn't contain the value checked you can use either of the following Locator Strategies:
xpath:
//div[@id='TRUCK' and not(contains(@class,'checked'))]
css:
div#TRUCK:not(.checked)
Effectively, if your use case is to invoke click()
when the class attribute is not having the value checked, instead of presenceOf()
you need to use the ExpectedConditions elementToBeClickable() and you can use either of the following Locator Strategies:
xpath:
it('Clicking Truck button', function (done) { browser.driver .then(() => browser.wait(EC.elementToBeClickable(element(by.xpath("//div[@id='TRUCK' and not(contains(@class,'checked'))]")))), 30000, "Timed out button")
css:
it('Clicking Truck button', function (done) { browser.driver .then(() => browser.wait(EC.elementToBeClickable(element(by.css("div#TRUCK:not(.checked)")))), 30000, "Timed out button")
回答2:
This will check if checkbox is selected and if not will select it:
static async selectCheckbox(element: ElementFinder, markChecked: boolean) {
const isSelected = await elementt.isSelected();
if (isSelected !== markChecked) {
await elementt.click();
}
return;
}
来源:https://stackoverflow.com/questions/60184694/protractor-check-if-a-radio-button-is-checked-or-not