0

I am a complete newbie at JS and currently using it in a testing capacity along with the Karate framework to perform some UI testing. I am having the following problem:

There is a dropdown that has the following HTML:

<select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
<option value="4">Honda</option>
<option value="5">Toyota</option>
<option value="6">VW</option>
</select>

I used the following Karate method to get all text values under the dropdown:

def grabValues = scriptAll('#CarId', '_.textContent')

Once printed, the array look like this:

[
  "Mercedes\nBMW\nLexus\nHonda\nToyota\nVW\n"
]

console.log(Math.floor(Math.random() * (grabValues.length-1)))

When printed, it keeps giving me 0.0. I am assuming this is because the array contains new lines vs comma delimitated? If so, how can I get rid of the new lines and replace with commas?

Phil
  • 157,677
  • 23
  • 242
  • 245
hungryhippos
  • 617
  • 4
  • 15
  • 1
    _"I first grabbed all values from a dropdown"_... How did you _grab_ those values? Perhaps that process could be improved to not return an array with a single string value. The issue is that `myArray.length` is `1` and `1 - 1` is `0` – Phil Feb 11 '22 at 02:14
  • FYI here's how you get a random array index ~ [Getting a random value from a JavaScript array](https://stackoverflow.com/q/4550505/283366) – Phil Feb 11 '22 at 02:19
  • @Phil I used a native method inside Karate. That's why I didn't show that part, I figured most folks here wouldn't be familiar with it, but here it is: let grabValues = scriptAll('#CarId', '_.textContent') Where "scriptAll" grabs all values under an element. #CarId is the xpath to the dropdown element and .textContent is the type of data I am grabbing, which is text. – hungryhippos Feb 11 '22 at 02:21
  • @Phil sorry about that and the confusion, I edited my question and added more details. – hungryhippos Feb 11 '22 at 03:19

2 Answers2

3

What you want is to get the text from each <option>

def grabValues = scriptAll('#CarId option', '_.textContent')

This will give you an array of text values like

["Mercedes","BMW","Lexus","Honda","Toyota","VW"]

To get a random index you would use

Math.floor(Math.random() * grabValues.length)
Phil
  • 157,677
  • 23
  • 242
  • 245
2

One line code is console.log(myArr[0].split('\n'))

OR

Let's assume : The array of String is stored in myArr

let myArr = ["ABC\nDEF\nGHI\nJKL\nMNO\nPQR\nSTU\nVWX\nYZA\n"]

To get the string from the array

let stringOfArr = myArr[0]

Storing the new array from the stringOfArr deleminated by '\n' in newArray

let newArray = stringOfArr.split('\n')

console.log(newArray)
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88