我认为 Cypress 在遇到新域时正在重置第二次测试,请参阅此评论 Change baseUrl during test
赛普拉斯更改父域以匹配 baseUrl,以避免在与父域不匹配的网站上导航时出现问题。赛普拉斯产品只是没有编码来处理更改 baseUrl 中间测试。
为了检查它,这个简单的测试反映了发生的情况
describe('changing domains', () => {
it('goes to example.com', () => {
cy.visit('http://example.com')
})
it('changes to example.net', () => {
cy.wait(10000)
cy.visit('http://example.net')
})
})
有几种方法可以(可能)避免该问题,但不确定是否适合您。
- 在第二个测试的早期使用虚拟调用进入新域,
describe('changing domains', () => {
it('goes to example.com', () => {
cy.visit('http://example.com')
})
it('changes to example.net', () => {
cy.visit('http://example.net')
cy.wait(10000)
cy.visit('http://example.net')
})
})
- 等待第一次测试,
describe('changing domains', () => {
it('goes to example.com', () => {
cy.visit('http://example.com')
cy.wait(10000)
})
it('changes to example.net', () => {
cy.visit('http://example.net')
})
})
理想的解决方案是将 FakeSMTP 服务器从测试中删除并以与 XHR 帖子被捕获和存根 cy.route() 相同的方式捕获邮件发送,然后您不必等待 10 秒,但我不需要'没有看到任何例子,所以假设它还不可能。也许会在原生事件到来的时候。
我查看了这篇帖子Testing an email workflow from end to end with Cypress,它使用递归创建了一个自定义命令来轮询服务器,直到电子邮件出现。它本质上就像一个 cypress 命令重试,所以你不会等待任意时间(正如@Jboucly 所说的应该避免),而是以 300 毫秒的增量等待,直到电子邮件到达。
Cypress.Commands.add('getLastEmail', email => {
function requestEmail() {
return cy
.request({
method: 'GET',
url: 'http://localhost:4003/last-email',
headers: {
'content-type': 'application/json',
},
qs: {
email,
},
json: true,
})
.then(({ body }) => {
if (body) {
return body;
}
// If body is null, it means that no email was fetched for this address.
// We call requestEmail recursively until an email is fetched.
// We also wait for 300ms between each call to avoid spamming our server with requests
cy.wait(300);
return requestEmail();
});
}
return requestEmail();
});
它确实应该有一个递归深度限制,以防万一事情没有按预期进行并且电子邮件永远不会到达。