我正在编写Cypress测试,我们的应用程序有一堆表单,它们都遵循一个特定的模式,首先是本地验证,然后是提交时的服务器验证.如果出现服务器错误,它会呼叫setCustomValidity
和reportValidity()
我遇到的问题是我想要编写一个如下所示的测试:
cy.intercept('POST', '/api**').as('apiRequest')
// ...test code to fill in fields
// Here I'm clearing the field I care about
cy.wrap($input).clear()
// The actual input I care about
cy.get('[name=zip]').type('00000')
cy.get('form [type=submit]').click()
cy.wait('@apiRequest').then((interception) => {
cy.get('[name=zip]').then(($input) => {
expect($input[0].validationMessage).to.eq(errorMessage)
})
})
然而,问题是在实际的应用程序代码中,expect($input[0].validationMessage).to.eq(errorMessage)
行是在onComplete
回调之前调用的.它看起来类似于:
function submitHandler() {
// This is what is intercepted by Cypress
makeAnApiCall({
variables: {
input: {
// ...
},
},
onCompleted(response) {
const addressResponse = response.createAddress
// ... the rest of the handling logic. If there are errors...
// This runs AFTER the cy.intercept callback is run so tests fail
addressResponse?.messages.forEach((message) => {
elementArray[message.field]?.setCustomValidity(message.help)
elementArray[message.field]?.reportValidity()
})
},
onError(error) {
// ...
},
})
}
您可以在上面看到API调用完成后的报告调用.这是有道理的,因为Cypress 可能是为了监视它而包装它,其他等待它完成的人被称为after间谍回调.
我唯一的 idea 就是听间谍说:
cy.spy($input[0], 'reportValidity').as('validitySpy')
cy.wait('@validitySpy').then(() => {/* check validation here */})
但这不起作用或不受支持.总的来说,我是不是做错了,或者我应该怎么做?最好不要将数据属性注入DOM以跟踪API请求的状态.