【问题标题】:how to get property out of json response in cypress如何从赛普拉斯的 json 响应中获取属性
【发布时间】:2020-07-22 08:07:24
【问题描述】:

我有 cypress 请求调用返回 Json 数组 {ids:[one, two, three]} 如何从响应正文中解析出其中一个数组值并将其传递给下一个测试?

【问题讨论】:

    标签: json cypress


    【解决方案1】:

    考虑到给定的信息,我猜你想要的是Asserting Network Calls from Cypress Tests

    cypress-example-recipes中有一个很好的例子

    我猜你可以做类似的事情

    describe('Test', () => {
      let ids;
    
      it('gets expected response', () => {
        cy.server()
        cy.route('GET', '/url').as('response')
        cy.visit("url")
       
        // log the request object
        cy.get('@response').then(console.log) 
      
        // confirm the request status
        cy.get('@response').should('have.property', 'status', 200)
    
        // confirm the request's response
        cy.get('@response').its('response').then((res) => {
          expect(res.body).to.deep.equal({
            "ids": ["one", "two", "three"]
          })
         
          // store the ids in a variable
          ids = JSON.parse(res.body)?.ids
        })
      })
    })
    

    【讨论】:

    • 尝试了大部分,这里的问题:当我做 ids = JSON.parse(res.body) 时,cypress 抱怨 json 中的无效字符
    • 如果你的回复真的是格式化{ids:[one, two, three]} - 那不是有效的JSON。请参考jsonlint.com 或进一步详细说明您真正想做的事情。
    • 我使用“cy.log”来打印值并且误导了......它实际上是有效的json并且它已经被解析到对象中;我使用“res.body.ids [0]”来获取数组的第一个成员并且有效
    • 很高兴它在这里工作!如果有帮助,请考虑接受此答案。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2021-08-08
    相关资源
    最近更新 更多