尝试使用我的 React 应用程序进行 Cypress 测试。
我正在从后端检索具有属性 expirationDate 的对象。它是一个格式为 YYYYMMDD 的整数。在我对应的
<input>
组件前端中,它呈现为 YYYY-MM-DD 字符串。
但是,该对象可以选择根本没有到期日期,而是表示为属性 -1 或 -2。这在
<input>
中显示为空字符串 ''。
因此我需要有条件地检查该值。我该如何使用 Cypress 来做到这一点?
我现在最接近的是
cy.get('#input-expiration-date').should('have.value', expirationDate || '')
但这并不是对上述条件的真正准确测试。
使用
cy.intercept()
获取来自后端的值。
一般方法(可能会根据响应模式而有所不同):
cy.intercept('some-api-request').as('api')
// trigger the backend request/response
cy.get('button').click()
cy.wait('api').then(interception => {
const obj = interception.response.body; // extract object
const expirationDate = obj.expirationDate // and it's expirationDate
const hasNoExpiration = expirationDate === -1 && expirationDate === -2
cont expectedValue = hasNoExpiration ? '' :
`${expirationDate.slice(0,4)}-${expirationDate.slice(4,2)}-${expirationDate.slice(6,2)}`
cy.get('#input-expiration-date').should('have.value', expectedValue)
})
您还可以更进一步,通过存根消除任何后端变化
cy.intercept('some-api-request', {body: { expirationDate: -1 }).as('api')
// trigger the backend request/response
cy.get('button').click()
cy.wait('api')
cy.get('#input-expiration-date').should('have.value', '')
cy.intercept('some-api-request', {body: { expirationDate: '20220319' }).as('api')
// trigger the backend request/response
cy.get('button').click()
cy.wait('api')
cy.get('#input-expiration-date').should('have.value', '2022-03-19')
oneOf() 你可以使用。
Cypress 在内部使用 Chai,因此表达式在内部工作.should()
。
cy.get('#input-expiration-date')
.invoke('val')
.should('have.oneOf', [expirationDate, ''])
直接使用Chai
cy.get('#input-expiration-date').then($input => {
expect($input.val()).to.have.oneOf([expirationDate, ''])
})
不好的做法。
cy.get('#input-expiration-date')
.invoke('val')
.then(val => {
if (val === expirationDate) { // fails because page is still fetching
...
}
})
测试运行速度快于从服务器获取值的速度。您可以通过使用
cy.intercept()
等待对象获取并然后进行条件检查来避免此问题。
let expirationDate = 'YYYYMMDD'
cy.intercept(url).as('object')
cy.visit(...)
cy.wait('@object').then(object => {
if (object.expirationDate) {
cy.get('#input-expiration-date')
.should('have.value', expirationDate)
}
})
cy.get('#input-expiration-date').then(element => {
//and here you can have conditions and access the DOM element
})
cy.get('#input-expiration-date')
.invoke('val')
.then((val) => {
if (val == expirationDate) {
//Do something
} else if (val == '') {
// Do something
} else {
//Do something
}
})