Using jQuery with WebDriver (JAVA) - java

Hi all!
I use WebDriver to automate the test packets. Please help to solve one problem: does not work use the jQuery .. always get the error
org.openqa.selenium.WebDriverException: TypeError: $(...) is null
Testing code:
#Test
public void stage003() throws Exception {
Reporter.log("<p class=\"stageDescr\">Check for uniqueness of identifiers</p>");
JQSS("" +
"var D_id=\"\";" +
"$('[id]').each(function(){" +
"var ids = $('[id=\"'+this.id+'\"]');" +
"if(ids.length>1 && ids[0]==this) {" +
"D_id = D_id + \" \" + this.id;" +
"}" +
"});" +
"if (D_id==\"\") {" +
"return D_id = \"All ID's is unique\";" +
"} else {" +
"return D_id;" +
"}" +
"");
Reporter.log("<p class=\"stageOutline\"> </p>");
}
And
public void JQSS(String SC) {
String test = (String)((JavascriptExecutor) driver).executeScript(
SC
);
Reporter.log("<p>Testing report... "+test+ "</p>");
}
PS: jquery on the page is already connected

I found the problem - on the test page was also MooTols. I changed the $ sign on "jQuery" and it worked

Related

How to fix a error to write a text on a document-body html?

Good morning everybody, I am writing for you to help me for a method that contains an error.
I am trying to automatize a test for writing a text on a document.body.innerHTML with the method executeJavascript but it's block in a code line. What can I do to fix this error :
"org.openqa.selenium.JavascriptException: SyntaxError: unexpected
token: identifier".
Thanks for your help.
Here is my part of the code:
public void publishCommentInFeedback(String commentTxt) {
JLearnSelectorUtils
.findElementByCssSelector(".comment-pane .dbcomment-add A").click();
ActionUtils.switchToFrame(
JLearnSelectorUtils.findElementByCssSelector(".new-comment-container IFRAME")
);
ActionUtils
.executeJavascript("document.body.innerHTML = '" + commentTxt + "'");
ActionUtils.switchToDefaultContent();
JLearnSelectorUtils.findElementByCssSelector(".new-comment-container .btn").click();
ActionUtils.waitUntilElementVisible(60, ".fulldisplay-footer .wysiwyg-editor");
}
Missing ; at the end of the script:
ActionUtils.executeJavascript("document.body.innerHTML = '" + commentTxt + "'");
vs
ActionUtils.executeJavascript("document.body.innerHTML = '" + commentTxt + "';");
A different approach to find the body element:
String desiredText = "Kevens";
String scr = "document.getElementsByTagName('body')[0].innerHTML = '" + desiredText + "';";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
javascriptExecutor.executeScript(scr);

Unable to Select option from dropdown using JavascrtptExecutor

Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.

Why JSON Parser is giving, error org.json.JSONException: Expected a ':' after a key at 5 [character 6 line 1]

I am new in json and I have to get the value from web service response. I have used org.json library for this.Below is the sample json value:
{"tms_guid": "9LaHmoHpmTd811R",
   "recharge_status": "100",
   "message": "Transaction Successful",
   "response_time": {
      "verifyClient": 0.0281,
      "verifyGuid": 0.8695,
      "verifyOperator": 0.8698,
      "verifyMsid": 0.8698,
      "tms_guid": 1.6971,
      "queryErr": 7.4243,
      "StoringRecharge": 7.4358,
      "UpdatingBalance": 7.448
   }
}
My parsing JSON input string is :
private final static String JSON_TEST_DATA
= "{"
+ "   \"tms_guid\": \"9LaHmoHpmTd811R\", "
+ "   \"recharge_status\": \"100\", "
+ "   \"message\": \"Transaction Successful\", "
+ "   \"response_time\": { "
+ "      \"verifyClient\": 0.0281, "
+ "      \"verifyGuid\": 0.8695, "
+ "      \"verifyOperator\": 0.8698,"
+ "      \"verifyMsid\": 0.8698,"
+ "      \"tms_guid\": 1.6971,"
+ "      \"queryErr\": 7.4243,"
+ "      \"StoringRecharge\": 7.4358,"
+ "      \"UpdatingBalance\": 7.448"
+ "   }"
+ "}";
public static void main(final String[] argv) throws JSONException {
System.out.println(JSON_TEST_DATA);
final JSONObject testObj = new JSONObject(JSON_TEST_DATA);
System.out.println(testObj.toString());
}
Exception is as follows:
Exception in thread "main" org.json.JSONException: Expected a ':' after a key at 5 [character 6 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:310)
at com.kalsym.wsp.sp.icebeep.TestIceBeep.main(TestIceBeep.java:73)
I have seen similar post. But could not figure about the solution.
I am not seeing any problem. I have used same your code, but i am able to execute your program :
You can see my code, I have useed same java api too.
import org.json.JSONException;
import org.json.JSONObject;
public class TestCode {
private final static String JSON_TEST_DATA
= "{"
+ " \"tms_guid\": \"9LaHmoHpmTd811R\", "
+ " \"recharge_status\": \"100\", "
+ " \"message\": \"Transaction Successful\", "
+ " \"response_time\": { "
+ " \"verifyClient\": 0.0281, "
+ " \"verifyGuid\": 0.8695, "
+ " \"verifyOperator\": 0.8698,"
+ " \"verifyMsid\": 0.8698,"
+ " \"tms_guid\": 1.6971,"
+ " \"queryErr\": 7.4243,"
+ " \"StoringRecharge\": 7.4358,"
+ " \"UpdatingBalance\": 7.448"
+ " }"
+ "}";
public static void main (String arg[]) throws JSONException{
//System.out.println(JSON_TEST_DATA);
final JSONObject testObj = new JSONObject(JSON_TEST_DATA);
System.out.println(" --"+testObj.getString("recharge_status")+"\n");
System.out.println(testObj.toString());
}
}
may be some char-set problem.
I just had a similar problem, turned out that the JSON string copied from another place contained non-breaking space characters, hard to notice even under a debugger :). I was removing HTML tags from that string (received via email) with:
jstr = jstr.replaceAll("<.*?>", ""); // removes anything between < and >
and the result looked like valid JSON, but with these non-breaking spaces... This helped:
jstr = jstr.replaceAll("<.*?>|\u00a0", "");

`rtserver-id` turns to `rtserver - id` in java string

I have this code:
public void foo (){
String script =
"var aLocation = {};" +
"var aOffer = {};" +
"var aAdData = " +
"{ " +
"location: aLocation, " +
"offer: aOffer " +
" };" +
"var aClientEnv = " +
" { " +
" sessionid: \"\", " +
" cookie: \"\", " +
" rtserver-id: 1, " +
" lon: 34.847, " +
" lat: 32.123, " +
" venue: \"\", " +
" venue_context: \"\", " +
" source: \"\"," + // One of the following (string) values: ADS_PIN_INFO,
// ADS_0SPEED_INFO, ADS_LINE_SEARCH_INFO,
// ADS_ARROW_NEARBY_INFO, ADS_CATEGORY_AUTOCOMPLETE_INFO,
// ADS_HISTORY_LIST_INFO
// (this field is also called "channel")
" locale: \"\"" + // ISO639-1 language code (2-5 characters), supported formats:
" };" +
"W.setOffer(aAdData, aClientEnv);";
javascriptExecutor.executeScript(script);
}
I have two q:
when I debug and copy script value I see a member rtserver - id instead of rtserver-id
how can it be? the code throws an exception because of this.
Even if i remove this rtserver-id member (and there is not exception thrown)
I evaluate aLocation in this browser console and get "variable not defined". How can this be?
rtserver-id isn't a valid identifier - so if you want it as a field/property name, you need to quote it. You can see this in a Chrome Javascript console, with no need for any Java involved:
> var aClientEnv = { sessionId: "", rtserver-id: 1 };
Uncaught SyntaxError: Unexpected token -
> var aClientEnv = { sessionId: "", "rtserver-id": 1 };
undefined
> aClientEnv
Object {sessionId: "", rtserver-id: 1}
Basically I don't think anything's adding spaces - you've just got an invalid script. You can easily add the quotes in your Java code:
" \"rtserver-id\": 1, " +

Java vs. Net HTTP Client Performance

We call a webservice from our C# app which takes about 300ms using WCF (BasicHttpBinding). We noticed that the same SOAP call does only take about 30ms when sending it from SOAP UI.
Now we also implemented a test accessing the webservice via a basic WebClient in order to make sure that the DeSer-part of the WCf is not the reason for this additional delay. When using the WebClient class the call takes about 300ms as well.
Any ideas on why Java compared to C# is about 10x faster in this regard? Is there some kind of tweaking possible on the .NET side of things?
private void Button_Click(object sender, RoutedEventArgs e)
{
executeTest(() =>
{
var resultObj = client.getNextSeqNr(new WcfClient()
{
domain = "?",
hostname = "?",
ipaddress = "?",
loginVersion = "?",
processId = "?",
program = "?",
userId = "?",
userIdPw = "?",
userName = "?"
}, "?", "?");
});
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
executeTest(()=>
{
webClient.Proxy = null;
webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
webClient.Headers.Add("Content-Type", "application/xml");
webClient.Encoding = Encoding.UTF8;
var data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"SomeNamespace\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <ser:getNextSeqNr>" +
" <!--Optional:-->" +
" <clientInfo>" +
" <!--Optional:-->" +
" <domain>?</domain>" +
" <!--Optional:-->" +
" <hostname>?</hostname>" +
" <!--Optional:-->" +
" <ipaddress>?</ipaddress>" +
" <!--Optional:-->" +
" <loginVersion>?</loginVersion>" +
" <!--Optional:-->" +
" <processId>?</processId>" +
" <!--Optional:-->" +
" <program>?</program>" +
" <!--Optional:-->" +
" <userId>*</userId>" +
" <!--Optional:-->" +
" <userIdPw>?</userIdPw>" +
" <!--Optional:-->" +
" <userName>?</userName>" +
" </clientInfo>" +
" <!--Optional:-->" +
" <name>?</name>" +
" <!--Optional:-->" +
" <schema>?</schema>" +
" </ser:getNextSeqNr>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
string result = webClient.UploadString("http://server:8080/service", "POST", data);
});
}
Am I missing something here? Any idea would be helpful... ;-)
Kind regards,
Sebastian
I just found the reason for this.
It's the 100-Expect Continue HTTP Header and the corresponding implementation in .NET. The .NET client wait 350ms as default on the server. This causes the delays. Java seems to have other default values here...
Just add the following line of code very early in your code:
System.Net.ServicePointManager.Expect100Continue = false;
Cheers!

Categories

Resources