我怎么等曲奇做好呢? [英] How do I wait until a cookie is set?
本文介绍了我怎么等曲奇做好呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为应用程序的登录功能编写验收测试。在某个时候,我想要仔细检查cookie的过期时间。
单击"Login"按钮后,将向我的服务器发送一个GraphQL查询,该服务器使用JWT进行响应。收到JWT后,应用程序使用设置cookiedocument.cookie = ...
在我的Cypress测试中,我通过以下方式检查令牌:
Then("sa session s'ouvre pour {SessionDurationType}", expectedDuration => {
cy.get('@graphql').then(() => {
cy.wait(1000)
cy.getCookie('token').then(cookie => {
const tokenDuration = getTokenDuration(cookie.value)
expect(tokenDuration.asSeconds()).to.equal(expectedDuration.asSeconds())
})
})
})
使用cy.get('@graphql')
,我正在等待GraphQL查询返回响应。别名定义如下:
cy.stub(win, 'fetch', fetch).as('graphql')
收到后,应用程序设置cookie。
我的问题是我不喜欢以下呼叫:
cy.wait(1000)
如果没有该调用,我总是得到一个未定义的cookie。
有没有办法在可能远小于1000ms的时间内获得该cookie?我尝试了很多方法都没有成功。
推荐答案
您必须编写递归承诺函数,请尝试以下操作
function checkCookie() {
// cy.getCookie returns a thenebale
return cy.getCookie('token').then(cookie => {
const tokenDuration = getTokenDuration(cookie.value);
// it checks the seconds right now, without unnecessary waitings
if(tokenDuration.asSeconds() !== expectedDuration.asSeconds()) {
// waits for a fixed milliseconds amount
cy.wait(100);
// returns the same function recursively, the next `.then()` will be the checkCookie function itself
return checkCookie();
}
// only when the condition passes returns a resolving promise
return Promise.resolve(tokenDuration.asSeconds());
})
}
Then("sa session s'ouvre pour {SessionDurationType}", expectedDuration => {
cy.get('@graphql').then(() => {
checkCookie()
.then(seconds => {
expect(seconds).to.equal(expectedDuration.asSeconds())
})
})
})
请注意,该函数必须改进,因为
- 我没有将
expectedDuration
等参数化(这超出了向您演示如何做到这一点的范围) - 如果没有循环计数器检查,它将永远等待
但它可以工作(我在回复您之前签入了另一个上下文),如果您有更多问题,请分享"工作中"的GitHub回执,以便我可以克隆并使用您自己的解决方案进行检查。
如果😉不够清楚,请告诉我
更新
我们(me和Tommaso)编写了一个插件来帮助您进行此类检查,其名称为cypress-wait-until。
请为此感谢Open Source Saturday社区,我们在其中一个星期六😊期间开发了它
这篇关于我怎么等曲奇做好呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文