【问题标题】:Cypress intercept, traverse and assert REST API response against UI elementsCypress 针对 UI 元素拦截、遍历和断言 REST API 响应
【发布时间】:2021-09-13 16:19:33
【问题描述】:

我正在尝试针对我的 UI 验证 API 响应数据,但在遍历 JSON 响应时遇到了问题。

场景是这样的:

#1 点击触发REST调用的按钮//返回下面的响应/json数组对象

[
  {
    "id": "Spain 1",
    "content": "77842B03FF9DE970C1256E520058DFFE\nSpain 1 \n",
    "lastUpdatedAt": "2021-05-24T06:50:00Z",
  },
  {
    "id": "Spain 2",
    "content": "9DED7F8F2CE195C7C125740C00366F52\nSpain 2 \n",
    "lastUpdatedAt": "2021-05-24T06:48:00Z",
  },
  {
    "id": "Spain 3",
    "content": "7D2C1C4E881560F3C1256E520058E01E\nSpain 3 \n",
    "lastUpdatedAt": "2021-05-24T06:46:00Z",
  }
]

#2 在 UI 中,我有一个包含 x 个下拉选项的下拉菜单,具体取决于上述响应的大小。由于它在数组中有 3 个 JSON 对象,因此下拉菜单将有 3 个选项 [Spain 1, Spain 2, Spain 3]。

#3 选择下拉选项,将在 UI 元素中显示响应 .content ('.ui-content') 例如:下拉值:Spain 1 将在 UI 元素中呈现 77842B03FF9DE970C1256E520058DFFE\nSpain 1 \n

#4 迭代所有下拉选项 [西班牙 1 到 3] 以验证适当的内容。

到目前为止,我已经编写了以下代码,但我无法遍历阻止我针对 UI 元素开发进一步验证的 JSON 值。

cy.wait('@portmemo').its('response.statusCode').should("eq", 200); //Passes
  cy.get('@portmemo').its('response')
    .then((response) => {
      // cy.log(response.body);//prints all body
      cy.log(response.body[0].id); //prints blank
      cy.log(response.body[0].lastUpdatedAt); //prints blank
      cy.log(response.body[0].content);//prints blank
      // cy.get('.ui-content').should('have.text', response.body[0].content);
    })

也尝试使用“cy.get('@portmemo').its('response.body')”但没有运气。 'response' 内的 then 是否不被识别为 JSON 对象本身?或者我错过了什么?

【问题讨论】:

  • 什么是console.log(response.headers['content-type'])?应该是application/json; charset=utf-8
  • 非常有效的点@Sarah,它给了text/plain; charset=utf-8。因此,它不是 JSON 格式。我会尽快解析并添加完整的解决方案。
  • 我觉得你需要链.then(response => response.json()),请看我之前删除的答案。

标签: cypress


【解决方案1】:

谢谢@Sarah,你的评论真的很有帮助,我做到了。

添加包含更多详细信息的附加答案。

cy.get('@portmemo').its('response.body')
    .then((response) => {
     // If the response's content-type is text/plain then convert to JSON format first           
      var json = JSON.parse(response);
      cy.log(json.length)//3
      for (var i = 0; i < json.length; i++) {
        cy.log(json[i].id)
        CurrentSchedule.selectBerthDropdown(json[i].id);
        CurrentSchedule.verifyPortMemoDetailsInPopUp(json[i].content);
      }
   })

【讨论】:

    【解决方案2】:

    使用.json()方法试试,

    cy.wait('@portmemo').its('response.statusCode').should("eq", 200);
    cy.get('@portmemo')
      .its('response')                      
      .then(response => response.json())   
      .then(json => {
        cy.log(json[0].id); 
        cy.log(json[0].lastUpdatedAt); 
        cy.log(json[0].content);
        cy.get('.ui-content')
          .eq(0)
          .should('have.text', json[0].content);
      })
    

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2014-07-14
      • 1970-01-01
      • 2017-06-11
      • 2011-07-22
      相关资源
      最近更新 更多