等待 Cypress each() 函数完成

wait for Cypress each() function to finish

我正在调用一个函数 populateArray,该函数使用 children() 函数在页面上选取元素。我想将属性值存储到 using each() 函数中。 这是我正在做的

static populateArray(){
let arr = []

 cy.xpath(NODE_PREVIEW_PANEL).children(NODE_TYPE)
                 .each((element, index, list) => arr.push(cy.wrap(element).invoke('attr', 'data-testid')))
}

问题是当我通过将它分配给一个变量来调用这个函数时

actualArray = ArticlePage.populateArray()

它不等待底层的 each() 函数完全完成。它只是选择部分价值和收益。我希望 actualArray 只有在 populateArray 完全解析后才具有值。

使用 Cypress.Promise 怎么样?来自文档

Cypress is promise aware so if you return a promise from inside of commands like .then(), Cypress will not continue until those promises resolve

const populateArray = () => {
  return new Cypress.Promise((resolve, reject) => {
    let arr = []
    cy.xpath('//ul')
      .children('li')
      .each(element => arr.push(element.attr('data-testid'))) // NOTE different push
      .then(() => {
        return resolve(arr)
      })
  })
}

调用 await(测试必须是异步的),

it('gets the array', async () => {

  const actualArray = await ArticlePage.populateArray();
  expect(actualArray).to.deep.equal(['1', '2', '3']);  // whatever is in 'data-testid'

})

由于 .each() 可以链接 - 您可以链接 .then 并在 .each() 过程完成后键入您需要执行的代码:


static populateArray(){
    let arr = []

    cy.xpath(NODE_PREVIEW_PANEL).children(NODE_TYPE)
        .each((element, index, list) => arr.push(arr.push(element.attr('data-testid')))
            .then(list => {
                cy.wrap(arr).as('actualArray')
            })
}

并在测试代码中

populateArray()
cy.get('@actualArray')
    .then(actualArray => {
        //code that needs the array data
    })

另一个答案使用 custom commands

Cypress.Commands.add("populateArray", (parentSelector, childSelector, arrayAllias) => {
    let arr = []

    cy.xpath(parentSelector).children(childSelector)
        .each((element, index, list) => arr.push(element.attr('data-testid')))
        .then(()=>{
            cy.wrap(arr).as(arrayAllias)
        })
})

并在测试代码中

cy.populateArray(NODE_PREVIEW_PANEL, NODE_TYPE, 'actualArray')
cy.get('@actualArray')
    .then(actualArray => {
        //code that needs the array data
    })