使用 Cypress 等待 XHR 轮询中的特定响应

Per*_*röm 6 javascript xmlhttprequest cypress

我有一个 cypress 规范,我想用它来测试我网站上的一个函数,该函数轮询第三方 API,直到它收到正确的答案,然后显示更多信息供用户继续使用该函数。

我开始我的规范

cy.server();
cy.route('GET', '**/that-other-api/**').as('otherApi');
Run Code Online (Sandbox Code Playgroud)

我知道这部分有效。该路由列在 Cypress 测试 GUI 的顶部,我的otherApi别名是在运行时在命令列表中列出的 XHR 请求中附加的。

当用户(或我的测试)单击按钮时,站点将开始轮询该端点。当我status: success在响应中收到 a时,用户(或我的测试)将获得一个完整的选项下拉列表,并且可以继续。

我怎样才能让赛普拉斯等到我从 XHR 请求中得到特定响应(或达到赛普拉斯超时),然后继续前进?

网络请求的文档没有解释,如果这是可以或不可以。我试过了

cy.wait('@billectaAccounts').should('have.property', 'response.body.status', 'success');
Run Code Online (Sandbox Code Playgroud)

只是为了看看东西是否有效

cy.wait('@billectaAccounts').should('have.property', 'status', 201);
Run Code Online (Sandbox Code Playgroud)

两者都抛出错误:

InvalidStateError:无法从“XMLHttpRequest”读取“responseText”属性:只有当对象的“responseType”为“”或“text”(为“json”)时,才能访问该值。

记录响应

cy.wait('@billectaAccounts').then(console.log);
Run Code Online (Sandbox Code Playgroud)

记录响应并显示我的状态变量在那里,但pending因为它仅在第一个请求中。

{
  "xhr": {
    "method": "GET",
    "url": "https://myapi/longToken",
    "id": "xhr193"
  },
  "id": "xhr193",
  "url": "https://myapi/longToken",
  "method": "GET",
  "status": 200,
  "statusMessage": "200 (OK)",
  "request": {
    "headers": {
      "Accept": "application/json, text/plain, */*"
    },
    "body": null
  },
  "response": {
    "headers": {
      "cache-control": "max-age=0, private, must-revalidate",
      "connection": "close",
      "content-type": "application/json; charset=utf-8",
      "date": "Tue, 24 Mar 2020 08:32:09 GMT",
      "etag": "W/\"f0d6999f3be78c3dc8eab419745ec489\"",
      "referrer-policy": "strict-origin-when-cross-origin",
      "server": "Cowboy",
      "vary": "Origin",
      "via": "1.1 vegur",
      "x-content-type-options": "nosniff",
      "x-download-options": "noopen",
      "x-frame-options": "SAMEORIGIN",
      "x-permitted-cross-domain-policies": "none",
      "x-request-id": "id",
      "x-runtime": "0.006788",
      "x-xss-protection": "1; mode=block"
    },
    "body": {
      "id": 721,
      "public_id": "longTokenId",
      "bank": "bank-id",
      "ssn": "ssn-number",
      "status": "pending",
      "created_at": "2020-03-24T09:32:05.362+01:00",
      "updated_at": "2020-03-24T09:32:06.028+01:00",
      "account_numbers": [],
      "token": "pollingToken"
    }
  },
  "duration": 230
}

Run Code Online (Sandbox Code Playgroud)

我宁愿不存根响应,很高兴对该 API 进行端到端测试。

任何帮助表示赞赏!