【问题标题】:Cypress: Access objects inside a array in API request赛普拉斯:在 API 请求中访问数组内的对象
【发布时间】:2021-09-28 02:50:08
【问题描述】:

我在用于登录测试的 API 调用中请求了一个 POST 方法,并收到了正文中包含许多对象的数组。我想使用 its 方法访问特定的客户端令牌,但它在一个数组中,我无法弄清楚如何访问,因为该数组没有“名称”。

cypress 中的请求:

it('Logar em um cliente com um usuário', function () {
    cy.request({
        method: 'POST',
        url: 'https://localhost:44332/api/Users/LoginDefault',
        body: {
            "username": "user",
            "password": "password"
        }
    }).its('body.token').then(res => console.log(res))

身体反应(续):

[
    {
        "user": "user1",
        "token": "token1"
    },
    {
        "user": "user2",
        "token": "token2"
    },
    {
        "user": "user3",
        "token": "token3"
    }
]

解决方案 它是这样工作的:

    it('Logar em um cliente com um usuário', function () {
        cy.request({
            method: 'POST',
            url: 'https://localhost:44332/api/Users/LoginDefault',
            body: {
                "username": "user",
                "password": "password"
            }
        }).its('body').then((res) => {
             const dadoToken = res[1].token
             expect(dadoToken).not.to.be.empty
        }) 
    })

【问题讨论】:

    标签: arrays json api cypress


    【解决方案1】:

    在这种情况下,body 响应是一个数组,所以您需要做的就是浏览数组。

    返回值是res,所以在这种情况下,它将是res[i].token,其中i 是您需要的数组中的对象。

    例如,res[2].token 将是“token3”。

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多