如何在Cypress中获取HTML属性值

6

在使用Selenium几年之后,我开始学习Cypress。在Selenium中,我经常使用GetAttribute()方法。现在我正在尝试使用Cypress完成同样的操作,从以下HTML元素中打印class属性值:

<input class="form-control ng-touched ng-pristine ng-valid" max="21" min="1" type="number">

这是我的代码:
cy.log(cy.get('input').invoke('attr', 'class'));

输出:

log Object{5}

我尝试使用Lakitna的cypress-commands (https://github.com/Lakitna/cypress-commands),代码如下:

cy.log(cy.get('input').attribute('class'));

输出:

输入图像说明

2个回答

10

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

cy.get('input').then(($input) => {
    cy.log($input.attr('class'));
});

screenshot1

或者

// with assertion
cy.get('input').should('have.attr', 'class').then(cy.log);

screenshot2


0
如果您正在寻找HTML标签的值并最终到达这里,那么这是最简单的方法:
            cy.get(`[data-testid="${key}"]`).then(($input) => {
            if($input.prop('nodeName') === "SELECT") {
                //Select corresponding input to value provided in dropdown lists

            } else {
                //Input each value provided into each field
                cy.get(`[data-testid="${key}"]`).clear().should('have.value', '').type(testMachine[key]).should('have.value', testMachine[key])
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接