Reputation: 23
I am working on Email Registration use case with Karate, where the user receives a registration email with a URL
I have this JSON response:
{
"links": [
"https://www.link1.com",
"https://www.link2.com",
"https://www.link3.com",
"https://www.link4.com",
"https://www.link5/go/there.com"
]
}
I would like to fetch the link which contains "/go/" in it and use it for my upcoming request as Given URL
* def goLink = someLogic??
Apologies if this was asked or example is available. Appreciate it if anyone can redirect me to resources. What logic I can use to get URL which contains "/go/" only? Then use that as my Given URL?
Note: I tried to write a simple Java Helper class, however that didn't help either
//Java Helper
public static String fetchRegistrationURL(List<Object> myList) {
for (Object el : myList) {
if (el.toString().contains("go")) {
myList.add(el);
} else {
}
}
return myList.get(0).toString();
}
Tried to pass this to feature:
* def utility = Java.type('Com.helpers.Utilities')
* def urlList = response.links
Then print '--urlList ==> ', urlList
* def acceptURL = utility.fetchRegistrationURL(urlList)
Then print '--register ==> ', acceptURL
Then status 200
This also failed. Hoping to see if @karate has a simpler solution
Versions:
<java.version>1.8</java.version>
<maven.compiler.version>3.8.1</maven.compiler.version>
<maven.surefire.version>2.22.2</maven.surefire.version>
<artifactId>karate-junit5</artifactId>
<karate.version>1.1.0</karate.version>
Upvotes: 1
Views: 227
Reputation: 58088
Use a "filter" or "find" operation. Please read the docs: https://github.com/karatelabs/karate#json-transforms
Here is a simple example that works. You can try paste this into a Karate test and study it.
* def response =
"""
{
"links": [
"https://www.link1.com",
"https://www.link2.com",
"https://www.link3.com",
"https://www.link4.com",
"https://www.link5/go/there.com"
]
}
"""
* def filtered = response.links.filter(x => x.includes('/go/'))
* match filtered == [ 'https://www.link5/go/there.com' ]
I've used the JS Array.filter()
method above, but karate.filter()
can also be used. Array.find()
may work better depending on your requirement.
Upvotes: 1