如何在Cypress中获取HTML属性值

Bor*_*kel 6 cypress

在使用 Selenium 几年后,我开始学习 Cypress。在 Selenium 中,我经常使用 GetAttribute() 方法。作为练习,我尝试对 Cypress 执行相同的操作,从以下 HTML 元素打印类属性值:

<input class="form-control ng-touched ng-pristine ng-valid" max="21" min="1" type="number">
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

cy.log(cy.get('input').invoke('attr', 'class'));
Run Code Online (Sandbox Code Playgroud)

输出:

log Object{5}
Run Code Online (Sandbox Code Playgroud)

我尝试将 Lakitna cypress-commands ( https://github.com/Lakitna/cypress-commands ) 与代码一起使用:

cy.log(cy.get('input').attribute('class'));
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

Sre*_*.Bh 10

cy命令是异步的,因此对于日志记录,您需要使用.then

cy.get('input').then(($input) => {
    cy.log($input.attr('class'));
});
Run Code Online (Sandbox Code Playgroud)

截图1

或者

// with assertion
cy.get('input').should('have.attr', 'class').then(cy.log);
Run Code Online (Sandbox Code Playgroud)

截图2