如何使用 cypress 将多个值设置为 .json 文件中的单个变量?

How to set multiple values to a single variable in .json file using cypress?

这是我在 .json 文件中写入提取值的代码。

cy.readFile(filename).then((product) => {
                    for (var i = 1; i < lens; i++) {
                        cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product/div[1]/mat-table/mat-row[' + i + ']/mat-cell[2]').then((txt) => {
                            var namee = txt.text()
                            cy.log(namee)
                            product.product_name = namee
                            cy.writeFile(filename, product, {flag: 'a+'})
                        })
                    }
            })

我想获取以下 .json 格式的数据。

{
“product_name”:[“Jam & Honey 女童常规版型 T 恤”、“儿童连帽衫”、“女式背心”]
}

您可以 select 多行并将它们转换为文本数组

cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product/div[1]/mat-table/mat-row')
  .find('mat-cell').eq(2)
  .then($cells => {
    const texts = [...$cells].map(cell => cell.innerText)  // array of texts
    cy.readFile(filename).then((product) => {
      product.product_name = texts
      cy.writeFile(filename, product)
    })
  })

也许使用 each 代替 for 循环

cy.readFile(filename).then((product) => {

  if (!product.product_name) product.product_name = [] // initial

  cy.xpath('/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/app-configurable-product/div[1]/mat-table/mat-row')
    .each($row => {
      cy.wrap($row).find('mat-cell').eq(2).invoke('text')
        .then(text => {
          product.product_name.push(text)
        })
    })
    .then(() => {
      cy.writeFile(filename, product)
    })
})