cypress: get inputs by name with variable

Viewed 47
const dates = {
    street: "Bauweg",
    house_number: "22",
    post_code: "22222"
}

describe("test legal-new site", () => {
    it("test for typing in input boxes", () => {
        for (let date in dates) {
            console.log(date)
            cy.get("input[name=date]")
                .focus()
                .clear()
                .type(dates[date])
                .blur()
        }
    })
})

Error-Message from cypress: Expected to find element: input[name=date], but never found it.

I wrote the date with backticks, but is not correct too. I checked with console.log(date): all o.k. All keys from dates are showed. What is wrong in this element? I think it s a format problem with date, but I don't know where I can find a solution.

2 Answers

You have a couple of options

  • from string concatenation
for (let date in dates) {
  const selector = "input[name=" + date + "]"
  cy.get(selector)
    ...
}
  • from template literal
for (let date in dates) {
  const selector = `input[name=${date}]`
  cy.get(selector)
    ...
}

There are a few things incorrect with your implementation.

const dates = {
    street: "Bauweg",
    house_number: "22",
    post_code: "22222"
}

describe("test legal-new site", () => {
    it("test for typing in input boxes", () => {
        // use lodash forEach to access the key values since dates is an object
        Cypress._.forEach(dates, function(value, key){
            console.log(date)
            // use template literal here `string${variable}`
            cy.get(`input[name=${key}]`)
                .focus()
                .clear()
                .type(value)
                .blur()
        }
    })
})
Related