我是 Cypress 的新手,正在尝试为用户名的某些文本输入编写断言。用户名的有效文本应满足两个条件,即:
- 文本只能包含英文字母。
- 文本长度应大于 1 且小于 20。
我的代码如下。
getUserFirstName(textInput) {
cy.get('[testid="user-self-update-form"]')
.get('input[name="firstName"]')
.clear()
.type(textInput)
.blur()
.invoke('val')
.should(($el) => {
expect($el).to
.match(/[a-zA-Z]+$/)
.to
.have
.greaterThan(1)
.to
.be
.lessThan(20)
}).then(() => {
cy.log("Invalid text input");
})
}
我的要求:当插入用户名文本时,上述测试应检查它是否满足强加的条件,如果不满足,则在控制台中记录一条消息。 我现在尝试分别对 4 个输入进行上述测试,即“abcd123”、“123”、“textwithmorethantwentyletters”和“belowtwenty”。对第一个输入文本“abcd123”运行此测试时。我该如何更正此代码?非常感谢您的帮助。
我收到以下错误,并且测试失败:
最佳答案
您可以尝试使用 Cypress .and()
链接条件
getUserFirstName(textInput) {
cy.get('[testid="user-self-update-form"]')
.find('input[name="firstName"]')
.clear()
.type(textInput).blur()
.invoke('val')
.should('match', /[a-zA-Z]+$/)
.and('have.length.gt', 1)
.and('have.length.lt', 20)
}
输入abc123
不符合第一个标准,您为什么认为测试会通过?
如果您只想记录日志而不希望测试失败,请尝试
getUserFirstName(textInput) {
cy.get('[testid="user-self-update-form"]')
.find('input[name="firstName"]')
.clear()
.type(textInput).blur()
.invoke('val')
.then(val => {
const lettersOnly = val.match(/[a-zA-Z]+$/)
const gt1 = val.length > 1
const lt20 = val.length < 20
if (!lettersOnly || !gt1 || !lt20) {
cy.log('Failed conditions')
// to fail the test now, throw an error
throw 'Failed conditions'
})
})
}
在第二个示例中,我没有使用 .should()
, .and()
或expect()
因为如果其中任何一个失败, Cypress 将无法通过该点的测试(并且不会检查其他条件)。
另请注意,.find(('input[name="firstName"]')
而不是.get('input[name="firstName"]')
因为您的目的是查找表单中输入的名字。
.get()
如果只有一个 'input[name="firstName"]'
也可能有效在页面上,但请注意,它会忽略前面的行并从根元素 <body>
查询 DOM .
关于javascript - Cypress 中带有嵌套查询的文本断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69701907/