arrays - Cypress:在 API 请求中访问数组内的对象

标签 arrays json api cypress

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

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))

body react (恢复):

[
    {
        "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
        }) 
    })

最佳答案

在这种情况下,主体响应是一个数组,因此您需要做的就是导航该数组。

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

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

关于arrays - Cypress:在 API 请求中访问数组内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68457451/

相关文章:

json - 基于字符串数组在 jq 中进行过滤

api - 如何搜索多个api服务

java - 使用 JAVA API 的 SOLR 索引

java - 如何使 && 作为字符串中的逻辑运算符

arrays - 如何将 bash 数组格式化为 JSON 数组

arrays - 显示数组/列表的内容

javascript - 使用像谷歌开发者工具这样的代码来跟踪 View ?

javascript - AngularJS http 从 xml api 获取

javascript - Google arrayToDataTable - 第 0 行的行类型无效

Java Arrays.sort(test) 对两个数组进行排序