【问题标题】:Cypress - Unable to get the Response Headers - API Automation赛普拉斯 - 无法获取响应标头 - API 自动化
【发布时间】:2022-04-22 05:30:04
【问题描述】:

我有一个使用 Cypress 的 API 自动化测试套件,我在其中一个测试中面临的问题之一是验证响应标头。

由于某种原因,我无法使用 Cypress 读取响应标头。

代码如下

cy.request({
  method:'GET',
  url:Cypress.env("Authorisationurl")+tokenId+'&decision=allow&acr_values=1',
  followRedirect: false,
  headers:{
      'Accept': "/*"
  }    
  }).then((response) => {
    const rbody = (response.body);
    cy.log(response.status)

    //THIS GOT ASSERTED TO TRUE
    expect(response.status).to.equal(302)

    //OPTION1
    cy.wrap(response.headers['X-Frame-Options']).then(() => {
      return response.headers['X-Frame-Options'];
    });

    
    //OPTION2
    return response.headers['X-Frame-Options']

    //OPTION3
    return response.headers
})

以上选项都没有给我标题信息。事实上,我也对执行顺序感到困惑。

这是我的输出。

下面的代码。

const rbody = (response.body);
cy.log(response.status)
cy.log(response)
expect(response.status).to.equal(302)
cy.log(response.headers)
cy.log(response.headers['X-Frame-Options'])
return response.headers['X-Frame-Options']

另外,不太确定 Object{9} 表示什么。谁能解释一下这里发生了什么。 我知道 Cypress 的执行流程,并且代码是作为回调函数写在 then 块中的。

选项 3 非常可怕,因为它会报错

cy.then() failed because you are mixing up async and sync code.

In your callback function you invoked 1 or more cy commands but then returned a synchronous value.

Cypress commands are asynchronous and it doesn't make sense to queue cy commands and yet return a synchronous value.

You likely forgot to properly chain the cy commands using another cy.then().

The value you synchronously returned was: Object{9}

任何人都可以在这里帮助我,因为正确的方法是什么。我知道 Cypress 非常快速且易于使用,但要摆脱 Selenium,我们需要通过有意义的错误消息让开发人员更容易编码。对象{9} 不是很有帮助。 另外,我需要使用 Cy.log 吗?因为打印的顺序不是我在代码中写的。非常感谢您抽出宝贵的时间。

【问题讨论】:

    标签: api cypress


    【解决方案1】:

    请这样使用: JSON.parse(JSON.stringify(response.headers))["X-Frame-Options"];

    【讨论】:

      【解决方案2】:

      “混合异步和同步代码”消息基本上是说您应该保持.then() 回调简单。

      但您可以链接多个.then() 以分别运行异步和同步代码。

      使用别名“返回”值。由于cy.request() 是异步的,因此您需要等待该值,而别名模式是可靠地执行此操作的最直接的方法。

      WRT Object{9},这是赛普拉斯记录复杂对象方式的结果。

      不要使用cy.log()调试东西,使用console.log()

      cy.request( ... )
        .then(response => {
          expect(response.status).to.equal(200)  // assert some properties
        })
        .then(response => response.headers)      // convert response to response.headers
        .as('headers')
      
      cy.get('@headers')
        .then(headers => {
          console.log(headers)
        })
      

      【讨论】:

        猜你喜欢
        • 2019-11-28
        • 2023-02-12
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        • 2021-12-02
        相关资源
        最近更新 更多