如何使用cypress获取无线电输入的值属性?

Rah*_*dav 0 javascript jquery e2e-testing cypress cypress-testing-library

我有一个无线电元素<input type="radio" name="gender" value="male" />

下面是我的赛普拉斯代码

cy.getAllByRole("radio").first().click()

如何获取 radio 元素的 value 属性?像这样的东西

const radioValue = cy.getAllByRole("radio").first().getValue() //"male"

Ala*_*paz 6

为了明确起见,这value="male"是一个属性,因此您可以使用

\n
cy.getAllByRole(\'radio\')\n  .first()\n  .invoke(\'attr\', \'value\')\n  .should(\'eq\', \'male\')           // assert it\n  .then(value => cy.log(value))   // or pass it down the chain\n
Run Code Online (Sandbox Code Playgroud)\n

该命令.invoke(\'val\')正在获取属性,并且仅适用于选定的单选选项,默认情况下是第一个选项。

\n

如果您尝试第二个选项,则会失败。

\n
<input type="radio" name="gender" value="male" />\n<input type="radio" name="gender" value="female" />\n
Run Code Online (Sandbox Code Playgroud)\n
cy.getAllByRole(\'radio\')\n  .eq(1)                     // take the second\n  .invoke(\'attr\', \'value\')\n  .should(\'eq\', \'female\')    // \xe2\x9c\x85 passes!\n\ncy.getAllByRole(\'radio\')\n  .eq(1)                     \n  .invoke(\'val\')\n  .should(\'eq\', \'female\')    // \xe2\x9d\x8c fails!\n\ncy.getAllByRole(\'radio\')\n  .eq(1)                     \n  .click()                  // change the selected item\n\ncy.getAllByRole(\'radio\')\n  .eq(1)          \n  .invoke(\'val\')\n  .should(\'eq\', \'female\')    // \xe2\x9c\x85 now it passes\n
Run Code Online (Sandbox Code Playgroud)\n

总之,您可以随时检查属性,但检查属性仅在单击操作发生后才起作用。

\n