获取复选框的选中值 - Material 设计

Getting the checked value of a checkbox - Material Design

我有一个页面使用基于 bootstrap 的基本管理 BSB Material 设计 layout

我很难从这个设计中的复选框中获取值。

示例复选框 'checked':

即使我添加了 data-cypress="mycheckbx" 属性,我发现 cypress 也找不到复选框控件。

所以我的问题是:在这种情况下如何获得 'checked' 属性?

使用的样式:

[type="checkbox"].filled-in:not(:checked)+label:before {
    width: 0;
    height: 0;
    border: 3px solid transparent;
    left: 6px;
    top: 10px;
    -webkit-transform: rotateZ(37deg);
    transform: rotateZ(37deg);
    -webkit-transform-origin: 20% 40%;
    transform-origin: 100% 100%
}

[type="checkbox"].filled-in:not(:checked)+label:after {
    height: 20px;
    width: 20px;
    background-color: transparent;
    border: 2px solid #5a5a5a;
    top: 0;
    z-index: 0
}

[type="checkbox"].filled-in:checked+label:before {
    top: 0;
    left: 1px;
    width: 8px;
    height: 13px;
    border-top: 2px solid transparent;
    border-left: 2px solid transparent;
    border-right: 2px solid #fff;
    border-bottom: 2px solid #fff;
    -webkit-transform: rotateZ(37deg);
    transform: rotateZ(37deg);
    -webkit-transform-origin: 100% 100%;
    transform-origin: 100% 100%
}

[type="checkbox"].filled-in:checked+label:after {
    top: 0;
    width: 20px;
    height: 20px;
    border: 2px solid #26a69a;
    background-color: #26a69a;
    z-index: 0
}

看来我需要做的就是:

cy.get('#pract-haspen').should('have.attr', 'checked')    

断言有效!

谢谢

如果 attr 对您不起作用,请尝试 prop:

cy.get('#pract-haspen').should('have.prop', 'checked')

由于上述 none 个解决方案对我有用,所以我这样做了:

cy.get('#element').should('be.checked')

来源:cypress documentation

相反的(未经检查的)断言是(参见官方 docs):

cy.get('#element').should('not.be.checked')

这个答案提出的问题考虑了断言测试。

如果你想获取值并在某处使用它,你可以简单地:

cy.get('#elementQuery').then(elem => {
   var value = elem.val()
   ...do anything you want, like if(value == 'on')...
})