How to use evalLocator method of com.intuit.karate.driver.WebDriver class

Best Karate code snippet using com.intuit.karate.driver.WebDriver.evalLocator

Source:WebDriver.java Github

copy

Full Screen

...117 }118 protected boolean isCookieError(Response res) {119 return res.getStatus() != 200;120 }121 private Element evalLocator(String locator, String dotExpression) {122 eval(prefixReturn(DriverOptions.selector(locator) + "." + dotExpression));123 // if the js above did not throw an exception, the element exists124 return DriverElement.locatorExists(this, locator);125 }126 private Element evalFocus(String locator) {127 eval(options.focusJs(locator));128 // if the js above did not throw an exception, the element exists129 return DriverElement.locatorExists(this, locator);130 }131 protected Variable eval(String expression, List args) {132 Json json = Json.object().set("script", expression).set("args", (args == null) ? Collections.EMPTY_LIST : args);133 Response res = http.path("execute", "sync").post(json);134 if (isJavaScriptError(res)) {135 logger.warn("javascript failed, will retry once: {}", res.getBodyAsString());136 options.sleep();137 res = http.path("execute", "sync").post(json);138 if (isJavaScriptError(res)) {139 String message = "javascript failed twice: " + res.getBodyAsString();140 logger.error(message);141 throw new RuntimeException(message);142 }143 }144 return new Variable(res.json().get("value"));145 }146 protected Variable eval(String expression) {147 return eval(expression, null);148 }149 protected List<String> getElementKeys() {150 // "element-6066-11e4-a52e-4f735466cecf" is the key to element in the W3C WebDriver standard151 // "ELEMENT" is a deviation from the W3C standard152 // explanation can be found here: https://github.com/karatelabs/karate/issues/1840#issuecomment-974688715153 return Arrays.asList("element-6066-11e4-a52e-4f735466cecf", "ELEMENT");154 }155 protected String getJsonForInput(String text) {156 return Json.object().set("text", text).toString();157 }158 protected String getJsonForLegacyInput(String text) {159 return Json.of("{ value: [ '" + text + "' ] }").toString();160 }161 protected String getJsonForHandle(String text) {162 return Json.object().set("handle", text).toString();163 }164 protected String getJsonForFrame(String text) {165 return Json.object().set("id", text).toString();166 }167 protected String selectorPayload(String locator) {168 if (locator.startsWith("{")) {169 locator = DriverOptions.preProcessWildCard(locator);170 }171 Json json = Json.object();172 if (locator.startsWith("/")) {173 json.set("using", "xpath").set("value", locator);174 } else {175 json.set("using", "css selector").set("value", locator);176 }177 return json.toString();178 }179 @Override180 public String elementId(String locator) {181 String json = selectorPayload(locator);182 Response res = http.path("element").postJson(json);183 if (isLocatorError(res)) {184 logger.warn("locator failed, will retry once: {}", res.getBodyAsString());185 options.sleep();186 res = http.path("element").postJson(json);187 if (isLocatorError(res)) {188 String message = "locator failed twice: " + res.getBodyAsString();189 logger.error(message);190 throw new RuntimeException(message);191 }192 }193 List<String> resultElements = res.json().<List<String>>get("$..", getElementKeys()).stream()194 .flatMap(List::stream)195 .collect(Collectors.toList());196 String resultElement = resultElements != null && !resultElements.isEmpty() ? resultElements.get(0) : null;197 if (resultElement == null) {198 String message = "locator failed to retrieve element returned by target driver: " + res.getBodyAsString();199 logger.error(message);200 throw new RuntimeException(message);201 }202 return resultElement;203 }204 @Override205 public List<String> elementIds(String locator) {206 return http.path("elements")207 .postJson(selectorPayload(locator)).json()208 .<List<String>>get("$..", getElementKeys()).stream()209 .flatMap(List::stream)210 .collect(Collectors.toList());211 }212 @Override213 public DriverOptions getOptions() {214 return options;215 }216 @Override217 public void setUrl(String url) {218 Json json = Json.object().set("url", url);219 http.path("url").post(json);220 }221 @Override222 public Map<String, Object> getDimensions() {223 return http.path("window", "rect").get().json().get("value");224 }225 @Override226 public void setDimensions(Map<String, Object> map) {227 http.path("window", "rect").post(map);228 }229 @Override230 public void refresh() {231 http.path("refresh").postJson("{}");232 }233 @Override234 public void reload() {235 // not supported by webdriver236 refresh();237 }238 @Override239 public void back() {240 http.path("back").postJson("{}");241 }242 @Override243 public void forward() {244 http.path("forward").postJson("{}");245 }246 @Override247 public void maximize() {248 http.path("window", "maximize").postJson("{}");249 }250 @Override251 public void minimize() {252 http.path("window", "minimize").postJson("{}");253 }254 @Override255 public void fullscreen() {256 http.path("window", "fullscreen").postJson("{}");257 }258 @Override259 public Element focus(String locator) {260 return retryIfEnabled(locator, () -> evalFocus(locator));261 }262 @Override263 public Element clear(String locator) {264 return retryIfEnabled(locator, () -> evalLocator(locator, "value = ''"));265 }266 @Override267 public Element input(String locator, String value) {268 return retryIfEnabled(locator, () -> {269 String elementId;270 if (locator.startsWith("(")) {271 evalFocus(locator);272 List<String> elements = http.path("element", "active").get()273 .json().<List<String>>get("$..", getElementKeys()).stream()274 .flatMap(List::stream)275 .collect(Collectors.toList());;276 elementId = elements != null && !elements.isEmpty() ? elements.get(0) : null;277 } else {278 elementId = elementId(locator);279 }280 Response response = http.path("element", elementId, "value").postJson(isSpecCompliant() ? getJsonForInput(value) : getJsonForLegacyInput(value));281 if (checkForSpecCompliance()) {282 if (response.json().get("$.value") != null) {283 String responseMessage = response.json().get("$.value.message");284 if (responseMessage.contains("invalid argument: 'value' must be a list")) {285 http.path("element", elementId, "value").postJson(getJsonForLegacyInput(value));286 specCompliant = false;287 } else {288 specCompliant = true;289 }290 } else {291 // did not complain that value should be a list so assume W3C WebDriver compliant moving forward292 specCompliant = true;293 }294 }295 return DriverElement.locatorExists(this, locator);296 });297 }298 @Override299 public Element click(String locator) {300 return retryIfEnabled(locator, () -> evalLocator(locator, "click()"));301 }302 @Override303 public Driver submit() {304 options.setPreSubmitHash(getSubmitHash());305 return this;306 }307 @Override308 public Element select(String locator, String text) {309 return retryIfEnabled(locator, () -> {310 eval(options.optionSelector(locator, text));311 // if the js above did not throw an exception, the element exists312 return DriverElement.locatorExists(this, locator);313 });314 }315 @Override316 public Element select(String locator, int index) {317 return retryIfEnabled(locator, () -> {318 eval(options.optionSelector(locator, index));319 // if the js above did not throw an exception, the element exists320 return DriverElement.locatorExists(this, locator);321 });322 }323 @Override324 public void actions(List<Map<String, Object>> actions) {325 http.path("actions").post(Collections.singletonMap("actions", actions));326 }327 @Override328 public void close() {329 http.path("window").delete();330 open = false;331 }332 @Override333 public boolean isTerminated() {334 return terminated;335 }336 public boolean isSpecCompliant() {337 return specCompliant == null || specCompliant;338 }339 public boolean checkForSpecCompliance() {340 return specCompliant == null;341 }342 @Override343 public void quit() {344 if (terminated) {345 return;346 }347 terminated = true;348 if (open) {349 close();350 }351 // delete session352 try {353 http.delete();354 } catch (Exception e) {355 logger.warn("session delete failed: {}", e.getMessage());356 }357 if (command != null) {358 command.close(true);359 }360 }361 @Override362 public String getUrl() {363 return http.path("url").get().json().get("value");364 }365 private String evalReturn(String locator, String dotExpression) {366 return eval("return " + DriverOptions.selector(locator) + "." + dotExpression).getAsString();367 }368 @Override369 public String html(String locator) {370 return retryIfEnabled(locator, () -> evalReturn(locator, "outerHTML"));371 }372 @Override373 public String text(String locator) {374 return retryIfEnabled(locator, () -> evalReturn(locator, "textContent"));375 }376 @Override377 public String value(String locator) {378 return retryIfEnabled(locator, () -> evalReturn(locator, "value"));379 }380 @Override381 public Element value(String locator, String value) {382 return retryIfEnabled(locator, () -> evalLocator(locator, "value = '" + value + "'"));383 }384 @Override385 public String attribute(String locator, String name) {386 return retryIfEnabled(locator, () -> evalReturn(locator, "getAttribute('" + name + "')"));387 }388 @Override389 public String property(String locator, String name) {390 return retryIfEnabled(locator, () -> evalReturn(locator, name));391 }392 @Override393 public Map<String, Object> position(String locator) {394 return position(locator, false);395 }396 @Override...

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1* def driver = { com.intuit.karate.driver.WebDriver driver }2* def locator = { com.intuit.karate.driver.Locator locator }3* def element = { com.intuit.karate.driver.Element element }4* def elements = { com.intuit.karate.driver.Elements elements }5* def result = { com.intuit.karate.driver.Result result }6* def args = { com.intuit.karate.driver.Args args }7* def arg = { com.intuit.karate.driver.Arg arg }8* def argType = { com.intuit.karate.driver.ArgType argType }9* def driver = driver { driver: 'chrome', headless: true }10* def locator = locator { id: 'foo' }11* def element = driver.evalLocator(locator)12* element.tagName() == 'div'13* element.attr('id') == 'foo'14* element.text() == 'hello world'15* element.css('color') == 'rgb(255, 0, 0)'16* element.css('background-color') == 'rgba(0, 0, 0, 0)'17* element.css('font-size') == '16px'18* element.css('font-family') == 'Times New Roman'19* element.css('font-weight') == '400'20* element.css('font-style') == 'normal'21* element.css('text-decoration') == 'none'22* element.css('text-align') == 'start'23* element.css('line-height') == 'normal'24* element.css('text-transform') == 'none'25* element.css('letter-spacing') == 'normal'26* element.css('word-spacing') == 'normal'27* element.css('white-space') == 'normal'28* element.css('word-wrap') == 'normal'29* element.css('word-break') == 'normal'30* element.css('overflow-wrap') == 'normal'31* element.css('tab-size') == '8'32* element.css('hyphens') == 'manual'33* element.css('display') == 'block'34* element.css('visibility') == 'visible'35* element.css('position') == 'static'36* element.css('top') == 'auto'37* element.css('right') == 'auto'38* element.css('bottom') == 'auto'39* element.css('left') == 'auto'40* element.css('z-index') == 'auto'41* element.css('box-sizing') ==

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1* def driver = karate.getWebDriver()2* def locator = {id: 'idOfElement'}3* def element = driver.evalLocator(locator)4* def driver = karate.getAppiumDriver()5* def locator = {id: 'idOfElement'}6* def element = driver.evalLocator(locator)7* def driver = karate.getAppiumDriver()8* def locator = {id: 'idOfElement'}9* def element = driver.evalLocator(locator)10* def driver = karate.getAppiumDriver()11* def locator = {id: 'idOfElement'}12* def element = driver.evalLocator(locator)13* def driver = karate.getAppiumDriver()14* def locator = {id: 'idOfElement'}15* def element = driver.evalLocator(locator)16* def driver = karate.getAppiumDriver()17* def locator = {id: 'idOfElement'}18* def element = driver.evalLocator(locator)19* def driver = karate.getAppiumDriver()20* def locator = {id: 'idOfElement'}21* def element = driver.evalLocator(locator)22* def driver = karate.getAppiumDriver()23* def locator = {id: 'idOfElement'}24* def element = driver.evalLocator(locator)25* def driver = karate.getAppiumDriver()26* def locator = {id: 'idOfElement'}27* def element = driver.evalLocator(locator)28* def driver = karate.getAppiumDriver()29* def locator = {id: 'idOfElement'}30* def element = driver.evalLocator(locator

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1* def driver = read('classpath:com/intuit/karate/driver/webdriver.js')2* def locator = { id: 'kw' }3* driver.evalLocator(locator) == { type: 'css', value: '#kw' }4* def driver = read('classpath:com/intuit/karate/driver/appium-driver.js')5* def locator = { id: 'kw' }6* driver.evalLocator(locator) == { type: 'id', value: 'kw' }7* def driver = read('classpath:com/intuit/karate/driver/android-driver.js')8* def locator = { id: 'kw' }9* driver.evalLocator(locator) == { type: 'id', value: 'kw' }10* def driver = read('classpath:com/intuit/karate/driver/ios-driver.js')11* def locator = { id: 'kw' }12* driver.evalLocator(locator) == { type: 'id', value: 'kw' }13* def driver = read('classpath:com/intuit/karate/driver/webdriver.js')14* driver.evalLocator({ id: 'kw' }) == { type: 'css', value: '#kw' }15* driver.evalLocator({ css: '#kw' }) == { type: 'css', value: '#kw' }16* driver.evalLocator({ name: 'wd' }) == { type: 'name', value: 'wd' }17* driver.evalLocator({ tag: 'input' }) == { type: 'tag', value: 'input' }18* driver.evalLocator({ link: '贴吧' }) == { type: 'link', value: '贴吧' }19* driver.evalLocator({ partialLink: '贴' }) == { type: 'partialLink', value: '贴' }20* driver.evalLocator({ className: 's_ipt' }) == { type: 'className', value: 's_ipt' }21* def driver = read('classpath

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1* def driver = karate.call('classpath:com/intuit/karate/driver/webdriver.feature').driver2* def locator = { id: 'email' }3* def locator = { css: '.form-control' }4* def locator = { name: 'email' }5* def locator = { linkText: 'Forgot Password?' }6* def locator = { partialLinkText: 'Forgot' }7* def locator = { className: 'form-control' }8* def locator = { tagName: 'input' }9* def locator = { className: 'form-control', index: 2 }10* def locator = { className: 'form-control', index: -1 }11* def locator = { className: 'form-control', index: 2, text: 'Email' }12* def locator = { className: 'form-control', index: 2, text: 'Email', exact: true }13* def locator = { className: 'form-control', index: 2, text: 'Email', exact: true, trim: true }14* def locator = { className: 'form-control', index: 2, text: 'Email', exact: true, trim: true, ignoreCase:

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1* def element = driver.findElement(locator)2* match element.getTagName() == 'a'3* match element.getLocation().getX() == 84* match element.getLocation().getY() == 85* match element.getSize().getWidth() == 726* match element.getSize().getHeight() == 167* match element.getCssValue('color') == 'rgba(255, 0, 0, 1)'8* match element.getCssValue('font-size') == '16px'9* match element.getCssValue('font-weight') == '700'10* match element.getCssValue('text-decoration') == 'none solid rgb(255, 0, 0)'11* def element = driver.findElement(locator)12* match element.getTagName() == 'a'13* match element.getLocation().getX() == 814* match element.getLocation().getY() == 815* match element.getSize().getWidth() == 7216* match element.getSize().getHeight() == 1617* match element.getCssValue('color') == 'rgba(255, 0, 0, 1)'18* match element.getCssValue('font-size') == '16px'19* match element.getCssValue('font-weight') == '700'20* match element.getCssValue('text-decoration') == 'none solid rgb(255, 0, 0)'21* def locator = driver.evalLocator('name=click me')22* def element = driver.findElement(locator)23* match element.getTagName() == 'a'24* match element.getLocation().getX() == 825* match element.getLocation().getY()

Full Screen

Full Screen

evalLocator

Using AI Code Generation

copy

Full Screen

1 * def locator = evalLocator('document.getElementById("myId")')2 * driver.find(locator)3 * driver.find(evalLocator('document.getElementById("myId")'))4 * def locator = evalLocator('document.getElementById("myId")')5 * driver.find(locator)6 * driver.find(evalLocator('document.getElementById("myId")'))

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful