Verify only one text/element that present in the page

How to verify only one text/element that can be present in the page

1 Like

Try copy&paste the following sample Test Case script into your Katalon Studio, then run it:

import org.openqa.selenium.WebElement

import com.kms.katalon.core.testobject.ConditionType
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import java.util.regex.Pattern
import java.util.regex.Matcher
import java.util.regex.MatchResult

TestObject makeTestObject(String id, String xpath) {
	return new TestObject(id).addProperty("xpath", ConditionType.EQUALS, xpath)
}

String url = "https://katalon-demo-cura.herokuapp.com/"

WebUI.openBrowser(url)
WebElement body = WebUI.findWebElement(makeTestObject("body", "//body"), 10)
String pageText = body.getText()
println pageText

// find all occurences of a string "Health" in the page text
Pattern ptn = Pattern.compile("Health", Pattern.CASE_INSENSITIVE)
Matcher matcher = ptn.matcher(pageText)
List<MatchResult> results = new ArrayList<>()
while (matcher.find()) {
	results.add(matcher.toMatchResult())
}

// I know, there are 4 "Health" in the page, so make sure
println "results.size()=" + results.size()
assert results.size() == 4

WebUI.closeBrowser()

This script checks the https://katalon-demo-cura.herokuapp.com/ page to have the “Health” string 4 times in the page text.

You can change the target URL and the pattern string as you like. Of course, you want to check the string to appear only 1ce.