1

I'm practicing and was trying to write in a file, all names and links of 'cars' from amazon. The following code is working but will only write one line in the txt file. How can I write the complete list? Maybe as an object?

Is there a better way to do this?

it.only("amazon cars", () => {
    cy.get("input#twotabsearchtextbox").type("cars{enter}");
    cy.get(".s-main-slot")
      .find("div>h2>a>span")
      .each((element) => {
        const elname = element.text();
        cy.wrap(element)
          .parent()
          .invoke("attr", "href")
          .then((href) => {
            cy.writeFile("element.txt", `${elname} and its link ${href}`);
          });
      });
  });
Vicko
  • 234
  • 4
  • 17

1 Answers1

1

You can use the append mode of cy.writefile().

cy.writeFile("element.txt", `${elname} and its link ${href}`, { flag: 'a+' });

Alternatively, ditch the .each() and use a mapping function instead. This way you only need to write once.

cy.get('.s-main-slot')
  .find('div>h2>a>span')
  .then($cars => {

    const descriptions = [...$cars].map(car => {  // car is raw element
      const elname = car.innerText;               // use DOM property innerText
      const href = car.parentElement.href;        // use DOM method parentElement
      return `${elname} and its link ${href}`
    })

    cy.writeFile('element.txt', descriptions.join('\n'))
  })

Or for a cleaner mapping function, take the parent of the span, the text will still be the same.

cy.get('.s-main-slot')
  .find('div>h2>a')
  .then($cars => {

    const descriptions = [...$cars].map(car => {
      return `${car.innerText} and its link ${car.href}`)
    })

    cy.writeFile('element.txt', descriptions.join('\n'))
  })

Or as an object, use a reducer to map

cy.get('.s-main-slot')
  .find('div>h2>a')
  .then($cars => {

    const asObject = [...$cars].reduce((obj, car) => {
      obj[car.innerText] = car.href;  // "Cars": "https://www.amazon.com...
      return obj;
    }, {})

    cy.writeFile("element.json", asObject)
  })