1

For example, I have this sample JSON object in pages folder which contains all the XPaths for specific page.

{
    "pageTitle1": "//*[@class='page-title' and text()='text1']",
    "pageTitle2": "//*[@class='page-title' and text()='text2']",
    "pageTitle_x" : "//*[@class='page-title' and text()='%s']"
}

 * def pageHome = read('classpath:/pages/pageHome.json')
 * click(pageHome.pageTitle_x) <-- how to properly replace %s in the string?

Update: I tried the replace function, not sure if this is the proper way.

* click(pageHome.pageTitle_x.replace("%s","new value"))

Don
  • 163
  • 12

1 Answers1

1

First a bit of advice. Trying to be "too clever" like this causes maintainability problems in the long run. I have said a lot about this here, please read it: https://stackoverflow.com/a/54126724/143475

That said, you can write re-usable JS functions that will do all these things:

* def pageTitle = function(x){ return "//*[@class='page-title' and text()='" + x "']" }

Now using that you can do this:

* click(pageTitle('foo'))

If you redesign the function even this may be possible:

* click(pageTitle(pageHome.pageTitle_x, 'foo'))

But see how things become more complicated and less readable. The choice is yours. Note that anything you can do in JS (e.g. String.replace()) will be possible, it is up to you and your creativity.

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    I'm asking this question because this is usual when automating using Selenium, dynamic xpath with %s is heavily used on Page Object Model. Thank you for the quick response Peter, I'll try what you've provided. – Don May 31 '21 at 06:52
  • @Don yes. my thoughts on Selenium and the "POM" are documented as point #7 here: https://hackernoon.com/the-world-needs-an-alternative-to-selenium-so-we-built-one-zrk3j3nyr – Peter Thomas May 31 '21 at 06:59