我如何等待 cookie 设置?

Lau*_*hel 5 javascript cookies cucumber graphql cypress

我正在为我的应用程序的登录功能编写验收测试。在某些时候,我想仔细检查 cookie 的过期时间。

单击“登录”按钮后,一个 graphql 查询将发送到我的服务器,该服务器以 Jwt 进行响应。收到 jwt 后,应用程序将设置 cookie

document.cookie = ...
Run Code Online (Sandbox Code Playgroud)

在我的 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())
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

使用cy.get('@graphql'),我正在等待 graphql 查询返回响应。别名定义如下:

cy.stub(win, 'fetch', fetch).as('graphql')
Run Code Online (Sandbox Code Playgroud)

收到后,应用程序会设置 cookie。

我的问题是我不喜欢以下调用:

cy.wait(1000)
Run Code Online (Sandbox Code Playgroud)

如果没有那个调用,我总是会得到一个未定义的 cookie。

有没有办法在远小于 1000 毫秒的时间内获取该 cookie?我尝试了很多事情但没有成功......

Nor*_*Ste 5

您必须编写一个递归 Promise 函数,请尝试以下操作

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())
      })
  })
})

Run Code Online (Sandbox Code Playgroud)

请注意,该功能必须改进,因为

  • 我没有参数化expectedDuration等(这超出了向您展示如何做到这一点的范围)
  • 它会永远等待而不检查循环计数器

但它有效(我在回复你之前检查了另一个上下文),如果你还有更多问题,请分享一个“工作”GitHub 存储库,以便我可以克隆并使用你自己的解决方案检查它。

如果还不够清楚请告诉我

更新

我们(Tommaso)编写了一个插件来帮助您进行此类检查,其名称为cypress-wait-until

请为此感谢开源周六社区,我们在其中一个周六开发了它