【问题标题】:How to send data correctly using writeFile with Cypress如何使用带有 Cypress 的 writeFile 正确发送数据
【发布时间】:2021-03-30 16:38:01
【问题描述】:

我正在练习并试图在一个文件中写入来自亚马逊的“汽车”的所有名称和链接。 以下代码正在运行,但只会在 txt 文件中写入一行。我怎样才能写出完整的清单?也许作为一个对象?

有没有更好的方法来做到这一点?

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}`);
          });
      });
  });

【问题讨论】:

    标签: javascript cypress writefile


    【解决方案1】:

    您可以使用append mode of cy.writefile()

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

    或者,放弃.each() 并改用映射函数。这样你只需要写一次。

    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'))
      })
    

    或者为了更简洁的映射函数,取span的父级,文本还是一样的。

    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'))
      })
    

    或者作为对象,使用reducer来映射

    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)
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-27
      • 2022-01-05
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2016-09-17
      • 2017-12-04
      • 2023-04-07
      相关资源
      最近更新 更多