Unable to verify IF element present or not

I want to click a button if the button is present. if it is not available move to the next step and proceed. Tried the below step

if (WebUI.verifyElementPresent(findTestObject(‘Object Repository/btn_AddNew’), 10)==true) {
WebUI.click(findTestObject(‘Object Repository/btn_AddNew’))
}

Script fails at the if conditional statement

2019-01-29 16:12:15.537 e[34mINFO e[0;39m e[36mc.k.k.c.webui.common.WebUiCommonHelper   -e[0;39m e[39mUnable to find the element located by 'By.xpath: //input[@type = 'submit' and @name = 'ctl00$TRNContentPlaceHolder$btnAdd' and @id = 'TRNContentPlaceHolder_btnAdd']'. Please recheck the objects properties to make sure the desired element is located. e[0;39m
2019-01-29 16:12:16.439 e[1;31mERRORe[0;39m e[36mc.k.k.core.keyword.internal.KeywordMain  -e[0;39m e[31m❌ com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/btn_AddNew' located by 'By.xpath: //input[@type = 'submit' and @name = 'ctl00$TRNContentPlaceHolder$btnAdd' and @id = 'TRNContentPlaceHolder_btnAdd']' not founde[0;39m
2019-01-29 16:12:16.951 e[1;31mERRORe[0;39m e[36mc.k.k.core.keyword.internal.KeywordMain  -e[0;39m e[31m❌ Unable to verify object 'Object Repository/btn_AddNew' is present (Root cause: com.kms.katalon.core.exception.StepFailedException: com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/TAS/Page_Transportation Asset System -/btn_AddNew' located by 'By.xpath: //input[@type = 'submit' and @name = 'ctl00$TRNContentPlaceHolder$btnAdd' and @id = 'TRNContentPlaceHolder_btnAdd']' not found)e[0;39m
2019-01-29 16:12:17.000 e[1;31mERRORe[0;39m e[36mc.k.k.core.main.RawTestScriptExecutor    -e[0;39m e[31m❌ if (verifyElementPresent(findTestObject("Object Repository/btn_AddNew"), 10) == true) FAILED.e[0;39m
e[31mReason:e[0;39m
e[31mcom.kms.katalon.core.exception.StepFailedException: Unable to verify object 'Object Repository/btn_AddNew' is present (Root cause: com.kms.katalon.core.exception.StepFailedException: com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/btn_AddNew' located by 'By.xpath: //input[@type = 'submit' and @name = 'ctl00$TRNContentPlaceHolder$btnAdd' and @id = 'TRNContentPlaceHolder_btnAdd']' not found)e[0;39m
e[31m	at com.kms.katalon.core.keyword.internal.KeywordMain.stepFailed(KeywordMain.groovy:36)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.stepFailed(WebUIKeywordMain.groovy:65)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.internal.WebUIKeywordMain.runKeyword(WebUIKeywordMain.groovy:27)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.builtin.VerifyElementPresentKeyword.verifyElementPresent(VerifyElementPresentKeyword.groovy:92)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.builtin.VerifyElementPresentKeyword.execute(VerifyElementPresentKeyword.groovy:68)e[0;39m
e[31m	at com.kms.katalon.core.keyword.internal.KeywordExecutor.executeKeywordForPlatform(KeywordExecutor.groovy:53)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords.verifyElementPresent(WebUiBuiltInKeywords.groovy:1434)e[0;39m
e[31m	at com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords$verifyElementPresent.call(Unknown Source)e[0;39m

The verifyElementPresent() method acts as an assertion, which means that if the method returns false, the test will stop, and the if statement won’t even be evaluated. The solution is to add a FailureHandling argument to the verifyElementPresent() method call. See the solution to a similar topic here:

Hi everyone,

We have already fixed the bug that caused the verifyElementPresent() and verifyElementNotPresent() keywords to throw an exception instead of returning false when the verified elements do not exist.

Please first check out the release note and click here to download if you want to try version 7.0.0 (beta) in advance.

Happy Testing!

Jass

1 Like

This exception is still appearing on Katalon 7.4.3.

Hi Jass,

We are using 7.5.5 version of Katalon but still facing some issue around verifyElementPresent property. In the example below: On first loop “Button1” and “Button2” exists while in 2nd only “Button2” exists. But Execution stops returning couldn’t find “Button1” with xpath=‘id=Button1’

for (int i = 1; i <= 2; i++) {
if (WebUI.verifyElementPresent(findTestObject(‘Automation/Button1’), 1) == true) {
WebUI.click(findTestObject(‘Automation/Button1’)) }
else if (WebUI.verifyElementPresent(findTestObject(‘Automation/Button2’), 1) == true) {
WebUI.click(findTestObject(‘Automation/Button2’))
} else {}

}

Could you please look into and help to fix?=

@vishal.gaikwad

Hi, please add a FailureHandling.CONTINUE_ON_FAILURE as the second parameter of the click(s).

WebUI.click(findTestObject(‘Automation/Button1’), FailureHandling.CONTINUE_ON_FAILURE)

@ThanhTo Thank yo for your prompt reply. We have already tried to use FailureHandling, but unfortunately returns same error. Could you please help to debug further? If you need any more details, feel free to tag me.

They actually need to add failure handling to the verifyElementPresent() calls, not the click() calls.

@vishal.gaikwad try this:

for (int i = 1; i <= 2; i++) {
    if (WebUI.verifyElementPresent(findTestObject(‘Automation/Button1’), 1, FailureHandling.CONTINUE_ON_FAILURE)) {
        WebUI.click(findTestObject(‘Automation/Button1’)) 
    }
    else if (WebUI.verifyElementPresent(findTestObject(‘Automation/Button2’), 1, FailureHandling.CONTINUE_ON_FAILURE)) {
        WebUI.click(findTestObject(‘Automation/Button2’))
    }
}

If FailureHandling.CONTINUE_ON_FAILURE doesn’t work, please try FailureHandling.OPTIONAL.

Ah my bad, I didn’t see that important statement. Thanks !

@Brandon_Hein @ThanhTo Thank you both of you, FailureHandling.CONTINUE_ON_FAILURE worked :slight_smile:

1 Like

Hi All, but even with using the failure handling set to continue, Still the test case is considered as a failed test case, which harms my reports and the velocity of the test suite, need urgent assistance with this matter. Thanks

Hi All,

I am facing the same issue as above, when element not present the test reports as failed instead of false. The version of Katalon is 7.5.5

Thanks

i try this, but my test case is considered as a failed test case. any suggestion? thanks

It depends what you are considering a failed test case. Does the script page have an X or does it only have an orange triangle on a statement?

If your script page has an X, review the Console tab and see what the error message was. If your script only has an orange triangle, that can mean that the statement didn’t pass, but it could be a passed test case if that was the way you organized your statement, such as an if / else condition and the condition was false (i.e. took the else path).

I know it’s been a few years since this has been updated, but my test also continues, but shows as failed in the Job Progress window, when I have a caught NoSuchElementException. I’m using KatalonStudio v8.6.8.

If you are using Selenium, then a “NoSuchElementException” could throw a failure to your code. If you are using WebUI keywords, then the same “NoSuchElementException” will not be a failure, but a warning. That’s assuming you are running as FailureHandling.OPTIONAL either within your statement or as your default setting.
Also, if you are running a Test Suite that has several Test Cases, then the “failure” of one Test Case does not stop the Test Suite from moving onto the next case.
If you can give us more information what you are doing and even an error log, then we may be able to give you more information.

Edit: The below might be a good read as well.

I think that’s what it was: the error was a failure because I was using Selenium. Is there a way for a caught error to not result in a failure when using Selenium within katalon? For some applications it is helpful to use WebElements instead of TestObjects.

My code is like:

@Keyword
public void waitForElementToDisappear() {
	String eleXpath = '//div[@id="elementId"]'
	WebDriver driver = DriverFactory.getWebDriver()
	WebDriverWait wait = new WebDriverWait(driver, 5)

	WebElement webElement = null
	try {
		webElement = driver.findElement(By.xpath(eleXpath))
	} catch (NoSuchElementException e) {
		// Element does not exist, no need to wait
	}
	if (webElement != null) {
		wait.until(ExpectedConditions.invisibilityOf(webElement))
	}
}

And the error is:

2024-03-08 09:42:36.667 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/TestName FAILED.
Reason:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@id="elementId"]"}

Maybe you need to get the “actual” name of the exception that is being thrown if “NoSuchElementException” is not the one that is getting caught. Or you can you double Exception, like below.

} catch (NoSuchElementException) {
		// Element does not exist, no need to wait
} catch (Exception e) {
		// well now, something has gone wrong
        WebUI.comment(e.getClass().getName())
        println(e.getClass().getName())
}

Edit: I just did a little experiment and the “NoSuchElementException” was caught, so maybe you are having another issue.

image

Edit2: One thing I just noticed is that my NoSuchElementException is being caught by:
com.kms.katalon.core.exception.NoSuchElementException
or, by its parent:
com.kms.katalon.core.exception.StepFailedException

and yours seems to (not) be caught by:
org.openqa.selenium.NoSuchElementException

I also noticed that if I put in a variable with the NoSuchElementException, like:
} catch (NoSuchElementException ex) { // this didn’t work
if did not work. The Exception found the error instead. When I did not include the variable, since I was not using it, the NoSuchElementException worked.
} catch (NoSuchElementException) { // this worked

1 Like

This is an interesting avenue to explore! I’m not getting the same results, though.

I’ve written a new method so I don’t have to keep editing my particular elements out to share.

For this method:

@Keyword
	public void waitForTextToBe(TestObject testObj, String expectedText, int timeout=120) {
		boolean textFound = WebUI.waitForElementAttributeValue(testObj, 'innerText', expectedText, timeout)
		if (!textFound) {
			throw new Exception("Expected text '${expectedText}' not found within ${timeout} seconds.")
		}

	}

I have written two unit tests. The positive test case doesn’t throw an error (as I expect). The negative test case does throw an error, but I’m not catching it still:

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject

import com.kms.katalon.core.testobject.ConditionType

import com.kms.katalon.core.testobject.TestObject

import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI

boolean negTestPass = false

int waitSec = 5

String xpath = "//div[@class='title solutions-title']"

WebUI.openBrowser('https://katalon.com/')

TestObject solutionsHeader = new TestObject().addProperty('xpath', ConditionType.EQUALS, xpath)

WebUI.waitForElementVisible(solutionsHeader, 10)

String expectedText = WebUI.getText(solutionsHeader)

println("text: ${expectedText}")

String unexpectedText = expectedText + 'FooBar'

// verify method doesn't fail when expected text displays

CustomKeywords.'Global.waitForTextToBe'(solutionsHeader, expectedText, waitSec)

// verify method does fail when expected text doesn't display

try {

CustomKeywords.'Global.waitForTextToBe'(solutionsHeader, unexpectedText, waitSec)

}

catch (Exception) {

// expected exception was thrown, do nothing

negTestPass = true

}

assert negTestPass : "Negative test failed."

WebUI.closeBrowser()

And this is my full console log:

2024-03-11 14:48:25.411 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2024-03-11 14:48:25.415 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/UnitTests/KeywordUTs/UTKW008_waitForTextToBe
2024-03-11 14:48:25.938 DEBUG testcase.UTKW008_waitForTextToBe         - 1: negTestPass = false
2024-03-11 14:48:25.939 DEBUG testcase.UTKW008_waitForTextToBe         - 2: waitSec = 5
2024-03-11 14:48:25.940 DEBUG testcase.UTKW008_waitForTextToBe         - 3: xpath = "//div[@class='title solutions-title']"
2024-03-11 14:48:25.942 DEBUG testcase.UTKW008_waitForTextToBe         - 4: openBrowser("https://katalon.com/")
2024-03-11 14:48:26.167 INFO  c.k.k.core.webui.driver.DriverFactory    - Starting 'Chrome' driver
Mar 11, 2024 2:48:26 PM org.openqa.selenium.remote.DesiredCapabilities chrome
INFO: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()`
2024-03-11 14:48:26.196 INFO  c.k.k.core.webui.driver.DriverFactory    - Action delay is set to 0 milliseconds
Starting ChromeDriver 121.0.6167.85 (3f98d690ad7e59242ef110144c757b2ac4eef1a2-refs/branch-heads/6167@{#1539}) on port 21751
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1710186508.478][WARNING]: This version of ChromeDriver has not been tested with Chrome version 122.
Mar 11, 2024 2:48:28 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
2024-03-11 14:48:28.670 INFO  c.k.k.core.webui.driver.DriverFactory    - sessionId = 4ee71c2b870f3099713809a68b2c8088
2024-03-11 14:48:28.693 INFO  c.k.k.core.webui.driver.DriverFactory    - browser = Chrome 122.0.0.0
2024-03-11 14:48:28.710 INFO  c.k.k.core.webui.driver.DriverFactory    - platform = Mac OS X
2024-03-11 14:48:28.712 INFO  c.k.k.core.webui.driver.DriverFactory    - seleniumVersion = 3.141.59
2024-03-11 14:48:28.713 INFO  c.k.k.core.webui.driver.DriverFactory    - proxyInformation = ProxyInformation { proxyOption=NO_PROXY, proxyServerType=HTTP, username=, password=********, proxyServerAddress=127.0.0.1, proxyServerPort=0, executionList="", isApplyToDesiredCapabilities=true }
2024-03-11 14:48:31.648 DEBUG testcase.UTKW008_waitForTextToBe         - 5: solutionsHeader = TestObject().addProperty("xpath", EQUALS, xpath)
2024-03-11 14:48:31.697 DEBUG testcase.UTKW008_waitForTextToBe         - 6: waitForElementVisible(solutionsHeader, 10)
2024-03-11 14:48:33.376 DEBUG testcase.UTKW008_waitForTextToBe         - 7: expectedText = getText(solutionsHeader)
2024-03-11 14:48:34.117 DEBUG testcase.UTKW008_waitForTextToBe         - 8: println(text: $expectedText)
text: Solutions
2024-03-11 14:48:34.146 DEBUG testcase.UTKW008_waitForTextToBe         - 9: unexpectedText = expectedText + "FooBar"
2024-03-11 14:48:34.147 DEBUG testcase.UTKW008_waitForTextToBe         - 10: Global.waitForTextToBe(solutionsHeader, expectedText, waitSec)
2024-03-11 14:48:34.480 INFO  k.k.c.m.CustomKeywordDelegatingMetaClass - Global.waitForTextToBe is PASSED
2024-03-11 14:48:34.480 DEBUG testcase.UTKW008_waitForTextToBe         - 11: try
2024-03-11 14:48:34.482 DEBUG testcase.UTKW008_waitForTextToBe         - 1: Global.waitForTextToBe(solutionsHeader, unexpectedText, waitSec)
2024-03-11 14:48:39.958 WARN  .k.b.WaitForElementAttributeValueKeyword - Object '' does not have attribute 'innerText' with value 'SolutionsFooBar'
2024-03-11 14:48:39.982 ERROR k.k.c.m.CustomKeywordDelegatingMetaClass - ❌ java.lang.Exception: Expected text 'SolutionsFooBar' not found within 5 seconds.
2024-03-11 14:48:39.994 DEBUG testcase.UTKW008_waitForTextToBe         - 12: catch (Exception Exception)
2024-03-11 14:48:40.033 DEBUG testcase.UTKW008_waitForTextToBe         - 1: negTestPass = true
2024-03-11 14:48:40.058 DEBUG testcase.UTKW008_waitForTextToBe         - 14: assert negTestPass : "Negative test failed."
2024-03-11 14:48:40.059 DEBUG testcase.UTKW008_waitForTextToBe         - 15: closeBrowser()
2024-03-11 14:48:40.347 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/UnitTests/KeywordUTs/UTKW008_waitForTextToBe FAILED.
Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.Exception: Expected text 'SolutionsFooBar' not found within 5 seconds.
	at Global.invokeMethod(Global.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at UTKW008_waitForTextToBe.run(UTKW008_waitForTextToBe:26)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:448)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:439)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:418)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:410)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:285)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:144)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:135)
	at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
	at TempTestCase1710186502562.run(TempTestCase1710186502562.groovy:25)
Caused by: java.lang.Exception: Expected text 'SolutionsFooBar' not found within 5 seconds.
	at Global.waitForTextToBe(Global.groovy:170)
	... 14 more

2024-03-11 14:48:40.419 ERROR c.k.katalon.core.main.TestCaseExecutor   - ❌ Test Cases/UnitTests/KeywordUTs/UTKW008_waitForTextToBe FAILED.
Reason:
org.codehaus.groovy.runtime.InvokerInvocationException: java.lang.Exception: Expected text 'SolutionsFooBar' not found within 5 seconds.
	at Global.invokeMethod(Global.groovy)
	at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:55)
	at UTKW008_waitForTextToBe.run(UTKW008_waitForTextToBe:26)
	at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
	at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
	at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:448)
	at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:439)
	at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:418)
	at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:410)
	at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:285)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:144)
	at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:135)
	at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
	at TempTestCase1710186502562.run(TempTestCase1710186502562.groovy:25)
Caused by: java.lang.Exception: Expected text 'SolutionsFooBar' not found within 5 seconds.
	at Global.waitForTextToBe(Global.groovy:170)
	... 14 more

2024-03-11 14:48:40.453 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/UnitTests/KeywordUTs/UTKW008_waitForTextToBe