skip to Main Content

I am failing to send a value from a method to xpath locator in locators.json file, How can I pass a value from javascript method to json file

locators.json

{
  "LoginPage":
   {
     "_Postal_TextField" : "//input[@data-testid='is-postal-input']",        
     "_Postal_Dropdown_List" : "//div[@class='relative']//span/p[text()={text}]"
   }
}

Expected xpath during runtime is:
//div[@data-testid="filter-tag-Location"]/p[text()="Thor"]'

Method.js

click_PostalDropdown(value)
{
  cy.clickElement("xpath",or.LoginPage._Postal_Dropdown_List(value))
}

2

Answers


  1. _Postal_Dropdown_List is not a function, it is a static field in the JSON. Instead, you can use string replace to insert your value variable.

    function click_PostalDropdown(value) {
      cy.clickElement(
        "xpath", 
        or.LoginPage._Postal_Dropdown_List.replace("{text}", value)
      );
    }
    
    Login or Signup to reply.
  2. To get the selector to read //div[@data-testid="filter-tag-Location"]/p[text()="Thor"] you will need to add the double-quotes around the value.

    Adding the double-quotes to the selector string would be ok if it’s inside a class, but it’s problematic if it’s a JSON file.

    You can do it in the method instead using template literal syntax, for example:

    const value = 'Thor'
    const pattern = "//div[@class='relative']//span/p[text()={text}]"
    const selector = pattern.replace('{text}', `"${value}"`)
    expect(selector).to.eq(`//div[@class='relative']//span/p[text()="Thor"]`)
    

    In the method:

    click_PostalDropdown(value) {
      const selector = or.LoginPage._Postal_Dropdown_List.replace('{text}',`"${value}"`)
      cy.clickElement("xpath", selector)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search