添加命令以检查文本和属性

add command to check text and attribute

我必须编写一个命令,其中我有一个文本字段,它应该有一个值,我必须检查该字段是否被禁用。禁用部分可能是个案,有时我不需要这个断言,但值检查将始终存在。 这是我到目前为止所做的:

Cypress.Commands.add('checkTextAndAttr', (selector, value) => {
 cy.get(selector).within(() => {
    cy.get('input').should('have.value', value)
})

这是禁用按钮的html:

<input disabled="" placeholder="my-field" type="tel" value="0,00" inputmode="numeric">

这是已启用的:

<input placeholder="my-field" type="tel" value="1 200,00" inputmode="numeric">

启用的字段是我可以在其中输入文本的字段。 未启用的字段是不能输入文本的字段,当计算完成时该字段将自行更新。

如何将禁用条件放入其中?

谢谢

我认为最好的方法是向您的命令添加一个附加参数。然后我们可以使用该参数有条件地更改 'have.attr''not.have.attr' 之间的断言。下面,我使用 ternary 来完成它。

Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled) => {
  cy.get(selector).within(() => {
    cy.get('input').should('have.value', value);
    cy.get('input').should(isDisabled ? 'have.attr' : 'not.have.attr', 'disabled')
  });
});

此外,如果你有一个压倒性数量的检查与另一个,你可以使 isDisabled 参数 optional/nullable,并使“默认”检查三元的错误结果. (如果将 'have.attr' 切换为错误语句,将 isDisabled 重命名为 isEnabled 可能有意义)

Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled?)
// with isDisabled false
cy.checkTextAndAttr('foo', 'bar', false);
// with isDisabled true
cy.checkTextAndAttr('foo', 'bar', true);
// with isDisabled undefined -- the `.should()` evaluates the same as false (both undefined and false are not true)
cy.checkTextAndAttr('foo', 'bar')