在 Cypress 测试中等待服务返回非空响应
在我的 Cypress 测试套件中,我有一个命令对电子邮件服务进行 API 调用,查找具有特定主题的电子邮件并返回该电子邮件的内容。
Cypress.Commands.add('getMostRecentEmail', subject => {
const requestUrl = new URL('api/mails', 'localhost')
requestUrl.port = '3000'
requestUrl.searchParams.append('subject', subject)
// TODO: wait for the following request to return a non-empty response.body
return cy.request('GET', requestUrl.toString()).then(response => {
return response.body[0].content[0].value
})
})
当我在本地运行测试时,效果很好,但是当在 CI 上运行测试时,它第一次失败,但当 Cypress 自动重试测试时成功。据推测,这是因为第一次尝试检索电子邮件时尚未收到电子邮件(电子邮件是在上述代码执行之前立即发送的)。
response.body
是服务返回的匹配电子邮件的数量,第一次发出请求时,这是空的,因此 response.body[0]
是 <代码>未定义。
赛普拉斯将此测试报告为“不稳定”,因为它第一次尝试时没有成功。
为了解决这个问题,我想在检索第一封电子邮件的内容之前等待请求返回非空响应。
In my Cypress test suite I have a command that makes an API call to an email service looking for an email with a particular subject and returns the content of that email.
Cypress.Commands.add('getMostRecentEmail', subject => {
const requestUrl = new URL('api/mails', 'localhost')
requestUrl.port = '3000'
requestUrl.searchParams.append('subject', subject)
// TODO: wait for the following request to return a non-empty response.body
return cy.request('GET', requestUrl.toString()).then(response => {
return response.body[0].content[0].value
})
})
This works fine when I run the test locally, but when the test is run on CI, it fails the first time, but succeeds when Cypress automatically retries the test. Presumably this is because the email has not yet been received the first time an attempt to is made to retrieve it (the email is sent immediately before the code above executes).
response.body
is the number of matching emails returned by the service, and the first time a request is made, this is empty, so response.body[0]
is undefined
.
Cypress reports this test as "flakey" because it doesn't succeed the first time it is attempted.
To fix this, I would like to instead wait for the request to return a non-empty response before retrieving the content of the first email.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请查看 https://slides.com/bahmutov/email-testing 演示文稿。特别是博客文章 https://www.cypress.io/blog/2021/05/24/full-testing-of-html-emails-using-ethereal-accounts/#retry-email-task 讨论如何重试获取电子邮件,因为它只能在某个未知时间后发生。
Take a look at https://slides.com/bahmutov/email-testing presentation. In particular, the blog post https://www.cypress.io/blog/2021/05/24/full-testing-of-html-emails-using-ethereal-accounts/#retry-email-task talks how to retry getting the email, since it can happen only after some unknown time.
为您的请求创建一个可以递归调用的函数:
替换:
为:
Create a function for your request that you can call recursively:
Replace:
With: