Return 嵌套换行的值

Return value from nested wrap

我刚开始使用 cypress,我对 return 从自定义命令中获取值有疑问。

我的应用程序中有多个表,在我的表中,我可以单击一行,这将打开一个包含更多详细信息的模式。所以我想构建一个命令来提取特定行的值,这样我就可以存储它们然后与模态值进行比较。

我也在尝试以一种跨不同表重用的方式执行此命令。但是我的 return 值有问题。这是我当前的命令:

Cypress.Commands.add(
  'getRowInformation',
  (rowsSelector, compareValue, mainProperty, nestedSelector) => {
    let rowNumber = -1
    const propertiesObject = {}

    /** 
     * get all the field in the all the rows that might contain the compareValue
     */
    cy.get(`[data-testid="${mainProperty}"]`).then($elements => {
      cy.wrap($elements)
        .each(($elementField, index) => {
          /**
           * Find first match and get the row index
           */
          if (rowNumber === -1 && $elementField.text() === compareValue) {
            rowNumber = index + 1
          }
        })
        .then(() => {
          /**
           * Access needed row
           */
          rowsSelector()
            .eq(rowNumber)
            .within(() => {
              cy.get(nestedSelector).then($property => {
                cy.wrap($property)
                  .each($prop => {
                    Object.assign(propertiesObject, { [$prop.attr('data-testid')]: $prop.text() })
                  })
                  .then(() => {
                    /**
                     * Return key value map, where key in data-testid
                     * and value is the element's text
                     */
                    return cy.wrap(propertiesObject)
                  })
              })
            })
        })
    })
  },
)

我在我的 it() 中将此命令调用为:

cy.getRowInformation(myCustomSelector, 'Compare value', 'testid', 'span').then(properties => {
    console.log('properties', properties)
    expect(true).to.be.true
})

我的自定义选择器:

myCustomSelector: () => cy.get('[data-testid="row"]'),

我的问题是我的 .then 在我的 it() 中得到的是 rowsSelector().eq(rowNumber) 而我需要的是创建的 propertiesObject。从文档中我找不到像这样嵌套的示例,所以你们认为这可行吗?

文档说 .within() yields the same subject it was given from the previous command.

所以看来您必须将 cy.wrap(propertiesObject) 移出内部回调并将其放在外部 then

您还可以在 .find() 中进行子句,这在语法上等同于 .within()

rowsSelector()
  .eq(rowNumber)
  .find(nestedSelector).each($prop => {
    Object.assign(propertiesObject, { [$prop.attr('data-testid')]: $prop.text() })
  })
  .then(() => cy.wrap(propertiesObject))  

您可能还想查看此 查找行号的部分。

我没试过,但也许

cy.contains(`[data-testid="${mainProperty}"]`, compareValue)  // only 1st match returned
  .invoke('index')
  .then((rowNumber) => {
    rowsSelector()
      .eq(rowNumber)
      .find(nestedSelector)
      .each($prop => {
        Object.assign(propertiesObject, { [$prop.attr('data-testid')]: $prop.text() })
      })
      .then(() => cy.wrap(propertiesObject))
  })