Cypress存储td值到自定义变量时代码运行报错如何解决?
代码不生效原因
Cypress 所有指令都是异步入队执行的,不会按代码编写顺序同步执行赋值逻辑。你声明的storedValue初始值为undefined,执行cy.contains(storedValue)时,前面cy.get链的.then()赋值逻辑还未实际运行,你传给cy.contains的参数是undefined,不符合参数类型要求,因此触发报错。
修复方案
把使用storedValue的逻辑放到.then()回调内部,保证调用时已经拿到了td的文本值:
cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').then(storedValue => { cy.contains(storedValue).should('exist'); })
如果需要在多步逻辑中复用该值,可以用Cypress别名机制存储:
// 存储为别名 cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').as('tdValue') // 后续使用时调用别名 cy.get('@tdValue').then(storedValue => { cy.contains(storedValue).should('exist') // 其他复用storedValue的逻辑都可以写在这里 })
内容的提问来源于stack exchange,提问作者dx584905
相关产品推荐
相关产品推荐

