Cypress:应用程序中是否有用于通知的事件侦听器



原则上,被测试的应用程序可以在任何时候抛出错误通知(通常是在某些事情没有正常工作时:服务器端(。我的问题是,我的柏树测试不会对这样的错误消息失败。

是否可以在柏树中为此类事件配置侦听器?如果弹出一个类似消息框的东西,它基本上总是会监听。

例如。正在侦听:

cy.contains('[data-e2e-notification-message-text]', 'ERROR: ')

您正在讨论主动被动元素检查之间的区别。

一般来说,主动等待通知是更好的

cy.contains('[data-e2e-notification-message-text]', 'ERROR: ', {timeout: 7000})
.should('not.exist')

比被动等待

cy.on('notification', (message) => {   // NOT REAL CODE - for illustration
if (message.includes('ERROR: ')) {
throw 'Notification occurred'      // fail the test
}
})

因为事件链涉及来自后端的异步调用,这可能在时间上有所不同。如果测试在通知到达之前结束,则会得到假阳性测试


如果操作是请求/响应类型,例如,则可以设置拦截

cy.intercept(...).as('notification')         // listen
cy.get(button).click()                       // action
cy.wait('@notification')                     // assert

如果实时服务器速度较慢,则添加存根

cy.intercept(url, { notification: 'Error: ' })          // immediately fake response
cy.get(button).click()                                          // action
cy.contains('[data-e2e-notification-message-text]', 'ERROR: ')  // assert

或者不要明确等待

cy.intercept(url, (req) => {
req.on('response', (res) => {
if (res.body.includes('Error:')) {
throw 'Notification of error'            // fail the test
}
})
cy.get(button).click()                                          // action

但假阳性结果的可能性也取决于时间。


如果您确实有一个定期检查元素的用例,您可以利用command:end事件。

您只能在事件处理程序中执行静态(jQuery(DOM查询(没有cy.()命令(。

// after every command look for notification
Cypress.on('command:end', () => {
const notification = Cypress.$('[data-e2e-notification-message-text]:contains(ERROR:)')
if (notification.length) {
throw 'Notification of error happened'    // fail the test
}
})

同样的警告也适用——如果测试比通知更快,这可能会很不稳定。

最新更新