//I created a loop to append an index number [1-16] to the end of an xpath selector (these are selectors for li items on a website, they're all the same except the index number on the end.) Then I want to assign that selector to an existing object array as a value to a key named 'link'. Then I want to call a custom command to loop through the array and click each key value pair. This is for the purpose of clicking the links(xpath selectors) and verifying the automation lands on the correct page which I verify with the url. Each object in the array has 2 key value pairs, link and url. I tried doing it where I just add the selectors to a regular array and it works fine in that manner. But when I try to add the selector to an array as part of an object I get errors. My code is below:
//Here is where I want to assign the newly concatenated xpath selector to my object array. Iv'e tried map, push, concat, assign and every other function I could find associated with arrays:
for (let i = 0; i < 17; i++) {
abtArr[i].concat({link: abtSel + `[${i}]`})
}
abtArr.forEach(item => {
aosPage
.click(item.link)
.verify.urlContains(item.url)
})
//object array (abtArr)
module.exports = [
{
link: '//*[@id="aspnetForm"]/div[4]/section/div[1]/div/div[2]/div/div[2]/div[1]/div/ul/li[1]',
url: 'https://www.aos.org/about-us/aos-membership.aspx'
},
{
link: '//*[@id="aspnetForm"]/div[4]/section/div[1]/div/div[2]/div[1]/div[2]/div[1]/div/ul/li[2]',
url: 'https://www.aos.org/about-us/lindleyana-magazine.aspx'
},
]
A Code Snippet (minimal reproducible example):
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
/*
const abtArr = [
{
link: '//*[@id="aspnetForm"]/div[4]/section/div[1]/div/div[2]/div/div[2]/div[1]/div/ul/li[1]',
url: 'https://www.aos.org/about-us/aos-membership.aspx'
},
{
link: '//*[@id="aspnetForm"]/div[4]/section/div[1]/div/div[2]/div[1]/div[2]/div[1]/div/ul/li[2]',
url: 'https://www.aos.org/about-us/lindleyana-magazine.aspx'
},
];
*/
// const abtSel = '//*[@id="aspnetForm"]/div[4]/section/div[1]/div/div[2]/div/div[2]/div[1]/div/ul/li';
const abtSel = '//*[@id="target"]/ul/li';
const abtArr = [];
for (let i = 1; i < 11; i++) {
const xPath = `${abtSel}[${i}]/a`;
const linkTag = getElementByXpath(xPath);
const someUrl = linkTag ? linkTag.href : null;
abtArr.push({link: xPath, url: someUrl})
}
console.log(abtArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<div id="target">
<ul>
<li><a href="example.com/1">Link</a></li>
<li><a href="example.com/2">Link</a></li>
<li><a href="example.com/3">Link</a></li>
<li><a href="example.com/4">Link</a></li>
<li><a href="example.com/5">Link</a></li>
<li><a href="example.com/6">Link</a></li>
<li><a href="example.com/7">Link</a></li>
<li><a href="example.com/8">Link</a></li>
<li><a href="example.com/9">Link</a></li>
<li><a href="example.com/10">Link</a></li>
</ul>
</div>