Uncle Sam
Uncle Sam

Reputation: 255

Convert array of elements received as a result of LocateAll() into text in Karate?

I am trying to get the list of project names from a table. Where by using locateAll() method I am able to get the list of elements but when I try to convert them into text value the result is null.

* def ProjectNames = locateAll("//div[@id='Projects']/@somePath")
* print ProjectNames 

Above code displays

[DriverElement@aef32g2
DriverElement@ahf38g2
DriverElement@ayf12gj
DriverElement@ae032f2]

But expectation is to get result as below:

[Project1
Project2
Project3
Project4]

For which I tried - * print ProjectNames.text.trim() but this displays nothing and step is passed. Instead when I execute it for particular index value it displays the text for that * print ProjectNames[0].text.trim(). How can I do it for complete list received? Thanks in advance!

Upvotes: 1

Views: 1701

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58088

Given the following HTML:

  <body>
    <div>first</div>
    <div>second</div>
  </body>  

If you have an array of anything, you can map over the array to transform it. Note that I'm using the new JS engine in Karate 1.0 :)

* def temp = locateAll('div')
* def vals1 = temp.map(x => x.text)
* match vals1 == ['first', 'second']

And a second way to do what you need is scriptAll(), refer the docs: https://github.com/intuit/karate/tree/master/karate-core#scriptall

* def vals2 = scriptAll('div', '_.textContent')
* match vals2 == ['first', 'second']

Upvotes: 1

Related Questions